message
stringlengths
2
49.9k
message_type
stringclasses
2 values
message_id
int64
0
1
conversation_id
int64
446
108k
cluster
float64
13
13
__index_level_0__
int64
892
217k
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Mahmoud was trying to solve the vertex cover problem on trees. The problem statement is: Given an undirected tree consisting of n nodes, find the minimum number of vertices that cover all the edges. Formally, we need to find a set of vertices such that for each edge (u, v) that belongs to the tree, either u is in the set, or v is in the set, or both are in the set. Mahmoud has found the following algorithm: * Root the tree at node 1. * Count the number of nodes at an even depth. Let it be evenCnt. * Count the number of nodes at an odd depth. Let it be oddCnt. * The answer is the minimum between evenCnt and oddCnt. The depth of a node in a tree is the number of edges in the shortest path between this node and the root. The depth of the root is 0. Ehab told Mahmoud that this algorithm is wrong, but he didn't believe because he had tested his algorithm against many trees and it worked, so Ehab asked you to find 2 trees consisting of n nodes. The algorithm should find an incorrect answer for the first tree and a correct answer for the second one. Input The only line contains an integer n (2 ≤ n ≤ 105), the number of nodes in the desired trees. Output The output should consist of 2 independent sections, each containing a tree. The algorithm should find an incorrect answer for the tree in the first section and a correct answer for the tree in the second. If a tree doesn't exist for some section, output "-1" (without quotes) for that section only. If the answer for a section exists, it should contain n - 1 lines, each containing 2 space-separated integers u and v (1 ≤ u, v ≤ n), which means that there's an undirected edge between node u and node v. If the given graph isn't a tree or it doesn't follow the format, you'll receive wrong answer verdict. If there are multiple answers, you can print any of them. Examples Input 2 Output -1 1 2 Input 8 Output 1 2 1 3 2 4 2 5 3 6 4 7 4 8 1 2 1 3 2 4 2 5 2 6 3 7 6 8 Note In the first sample, there is only 1 tree with 2 nodes (node 1 connected to node 2). The algorithm will produce a correct answer in it so we printed - 1 in the first section, but notice that we printed this tree in the second section. In the second sample: In the first tree, the algorithm will find an answer with 4 nodes, while there exists an answer with 3 nodes like this: <image> In the second tree, the algorithm will find an answer with 3 nodes which is correct: <image> Submitted Solution: ``` n=int(input()) if(n<6): print(-1) else: print(1,2) #print(1,3) print(1,4) for i in range(4,n): print(2,i+1) for i in range(n-1): print(1,i+1+1) ```
instruction
0
103,421
13
206,842
No
output
1
103,421
13
206,843
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Mahmoud was trying to solve the vertex cover problem on trees. The problem statement is: Given an undirected tree consisting of n nodes, find the minimum number of vertices that cover all the edges. Formally, we need to find a set of vertices such that for each edge (u, v) that belongs to the tree, either u is in the set, or v is in the set, or both are in the set. Mahmoud has found the following algorithm: * Root the tree at node 1. * Count the number of nodes at an even depth. Let it be evenCnt. * Count the number of nodes at an odd depth. Let it be oddCnt. * The answer is the minimum between evenCnt and oddCnt. The depth of a node in a tree is the number of edges in the shortest path between this node and the root. The depth of the root is 0. Ehab told Mahmoud that this algorithm is wrong, but he didn't believe because he had tested his algorithm against many trees and it worked, so Ehab asked you to find 2 trees consisting of n nodes. The algorithm should find an incorrect answer for the first tree and a correct answer for the second one. Input The only line contains an integer n (2 ≤ n ≤ 105), the number of nodes in the desired trees. Output The output should consist of 2 independent sections, each containing a tree. The algorithm should find an incorrect answer for the tree in the first section and a correct answer for the tree in the second. If a tree doesn't exist for some section, output "-1" (without quotes) for that section only. If the answer for a section exists, it should contain n - 1 lines, each containing 2 space-separated integers u and v (1 ≤ u, v ≤ n), which means that there's an undirected edge between node u and node v. If the given graph isn't a tree or it doesn't follow the format, you'll receive wrong answer verdict. If there are multiple answers, you can print any of them. Examples Input 2 Output -1 1 2 Input 8 Output 1 2 1 3 2 4 2 5 3 6 4 7 4 8 1 2 1 3 2 4 2 5 2 6 3 7 6 8 Note In the first sample, there is only 1 tree with 2 nodes (node 1 connected to node 2). The algorithm will produce a correct answer in it so we printed - 1 in the first section, but notice that we printed this tree in the second section. In the second sample: In the first tree, the algorithm will find an answer with 4 nodes, while there exists an answer with 3 nodes like this: <image> In the second tree, the algorithm will find an answer with 3 nodes which is correct: <image> Submitted Solution: ``` n = int(input()) if n == 2: print(-1) print(1, 2) elif n == 3: print(-1) print(1, 2) print(2, 3) else: for i in range(1, n): print(i, i +1) print(1, 2) for i in range(3, n + 1): print(2, i) ```
instruction
0
103,422
13
206,844
No
output
1
103,422
13
206,845
Provide a correct Python 3 solution for this coding contest problem. Given a tree T with non-negative weight, find the height of each node of the tree. For each node, the height is the distance to the most distant leaf from the node. Constraints * 1 ≤ n ≤ 10,000 * 0 ≤ wi ≤ 1,000 Input n s1 t1 w1 s2 t2 w2 : sn-1 tn-1 wn-1 The first line consists of an integer n which represents the number of nodes in the tree. Every node has a unique ID from 0 to n-1 respectively. In the following n-1 lines, edges of the tree are given. si and ti represent end-points of the i-th edge (undirected) and wi represents the weight (distance) of the i-th edge. Output The output consists of n lines. Print the height of each node 0, 1, 2, ..., n-1 in order. Example Input 4 0 1 2 1 2 1 1 3 3 Output 5 3 4 5
instruction
0
103,649
13
207,298
"Correct Solution: ``` import sys from heapq import heappop, heappush from typing import List def func(start: int) -> List[int]: global edges cost = [sys.maxsize] * n que = [(0, start)] cost[start] = 0 while que: acc, num = heappop(que) for weight, to in edges[num]: if weight + acc < cost[to]: cost[to] = weight + acc heappush(que, (weight + acc, to)) return cost if __name__ == "__main__": n = int(input()) edges = [[] for _ in range(n)] # type: ignore for _ in range(n - 1): s, t, w = map(int, input().split()) edges[s].append((w, t)) edges[t].append((w, s)) cost1 = func(0) max_ind = cost1.index(max(cost1)) cost2 = func(max_ind) max_ind2 = cost2.index(max(cost2)) cost3 = func(max_ind2) for i in range(n): print(max(cost2[i], cost3[i])) ```
output
1
103,649
13
207,299
Provide a correct Python 3 solution for this coding contest problem. Given a tree T with non-negative weight, find the height of each node of the tree. For each node, the height is the distance to the most distant leaf from the node. Constraints * 1 ≤ n ≤ 10,000 * 0 ≤ wi ≤ 1,000 Input n s1 t1 w1 s2 t2 w2 : sn-1 tn-1 wn-1 The first line consists of an integer n which represents the number of nodes in the tree. Every node has a unique ID from 0 to n-1 respectively. In the following n-1 lines, edges of the tree are given. si and ti represent end-points of the i-th edge (undirected) and wi represents the weight (distance) of the i-th edge. Output The output consists of n lines. Print the height of each node 0, 1, 2, ..., n-1 in order. Example Input 4 0 1 2 1 2 1 1 3 3 Output 5 3 4 5
instruction
0
103,650
13
207,300
"Correct Solution: ``` from sys import stdin from collections import defaultdict readline = stdin.readline #readline = open('GRL_5_B-in10.txt').readline def main(): n = int(readline()) g = defaultdict(list) for _ in range(n - 1): s, t, d = map(int, readline().split()) g[s].append([d, t]) g[t].append([d, s]) dp = defaultdict(dict) for i in postorder(g, n): for di, ti in g[i]: dp[i][ti] = di candidate = [v for k, v in dp[ti].items() if k != i] if candidate: dp[i][ti] += max(candidate) height = [None] * n for i in preorder(g, n): import operator candidate = list(dp[i].items()) candidate.sort(key=operator.itemgetter(1)) height[i] = candidate[-1][1] if candidate else 0 for d, t in g[i]: dp[t][i] = d if 1 < len(candidate): k = -1 if candidate[-1][0] != t else -2 dp[t][i] += candidate[k][1] print('\n'.join(map(str, height))) def postorder(g, n): visited = set() for i in range(n): if i in visited: continue parent_stack = [] dfs_stack = [(i, None)] while dfs_stack: u, prev = dfs_stack.pop() visited |= {u} dfs_stack.extend((t, u) for d, t in g[u] if t != prev) while parent_stack and parent_stack[-1] != prev: yield parent_stack.pop() parent_stack.append(u) while parent_stack: yield parent_stack.pop() def preorder(g, n): visited = set() for i in range(n): if i in visited: continue dfs_stack = [(i, None)] while dfs_stack: u, prev = dfs_stack.pop() visited |= {u} yield(u) dfs_stack.extend((t, u) for d, t in g[u] if t != prev) main() ```
output
1
103,650
13
207,301
Provide a correct Python 3 solution for this coding contest problem. Given a tree T with non-negative weight, find the height of each node of the tree. For each node, the height is the distance to the most distant leaf from the node. Constraints * 1 ≤ n ≤ 10,000 * 0 ≤ wi ≤ 1,000 Input n s1 t1 w1 s2 t2 w2 : sn-1 tn-1 wn-1 The first line consists of an integer n which represents the number of nodes in the tree. Every node has a unique ID from 0 to n-1 respectively. In the following n-1 lines, edges of the tree are given. si and ti represent end-points of the i-th edge (undirected) and wi represents the weight (distance) of the i-th edge. Output The output consists of n lines. Print the height of each node 0, 1, 2, ..., n-1 in order. Example Input 4 0 1 2 1 2 1 1 3 3 Output 5 3 4 5
instruction
0
103,651
13
207,302
"Correct Solution: ``` from heapq import heappop, heappush INF = 10 ** 20 def main(): n = int(input()) edges = [[] for _ in range(n)] for _ in range(n - 1): s, t, w = map(int, input().split()) edges[s].append((w, t)) edges[t].append((w, s)) def func(start): cost = [INF] * n que = [(0, start)] cost[start] = 0 while que: acc, num = heappop(que) for weight, to in edges[num]: if weight + acc < cost[to]: cost[to] = weight + acc heappush(que, (weight + acc, to)) return cost cost1 = func(0) max_ind = cost1.index(max(cost1)) cost2 = func(max_ind) max_ind2 = cost2.index(max(cost2)) cost3 = func(max_ind2) for i in range(n): print(max(cost2[i], cost3[i])) main() ```
output
1
103,651
13
207,303
Provide a correct Python 3 solution for this coding contest problem. Given a tree T with non-negative weight, find the height of each node of the tree. For each node, the height is the distance to the most distant leaf from the node. Constraints * 1 ≤ n ≤ 10,000 * 0 ≤ wi ≤ 1,000 Input n s1 t1 w1 s2 t2 w2 : sn-1 tn-1 wn-1 The first line consists of an integer n which represents the number of nodes in the tree. Every node has a unique ID from 0 to n-1 respectively. In the following n-1 lines, edges of the tree are given. si and ti represent end-points of the i-th edge (undirected) and wi represents the weight (distance) of the i-th edge. Output The output consists of n lines. Print the height of each node 0, 1, 2, ..., n-1 in order. Example Input 4 0 1 2 1 2 1 1 3 3 Output 5 3 4 5
instruction
0
103,652
13
207,304
"Correct Solution: ``` from collections import deque def solve(tree, root): def dfs1(): """各頂点の部分木内で最も遠い頂点(葉)までの距離を求める""" q1 = deque([root]) q2 = deque([root]) while q1: v = q1.pop() for nxt_v, cost in tree[v]: if nxt_v in par: continue else: par[nxt_v] = v q1.append(nxt_v) q2.append(nxt_v) while q2: v = q2.pop() for nxt_v, cost in tree[v]: if nxt_v == par[v]: continue else: dist1[v] = max(dist1[v], dist1[nxt_v] + cost) def dfs2(): """全方位木DPで各頂点の最も遠い頂点(葉)までの距離を求める""" q = deque([(root, 0)]) while q: v, par_d = q.pop() tmp = [(0, -1)] for nxt_v, cost in tree[v]: if nxt_v == par[v]: tmp.append((par_d + cost, nxt_v)) else: tmp.append((cost + dist1[nxt_v], nxt_v)) tmp = sorted(tmp, reverse=True) dist2[v] = tmp[0][0] for nxt_v, cost in tree[v]: if nxt_v == par[v]: continue if tmp[0][1] != nxt_v: q.append((nxt_v, tmp[0][0])) else: q.append((nxt_v, tmp[1][0])) par = {root: -1} dist1 = [0] * n dist2 = [0] * n dfs1() dfs2() return dist2 n = int(input()) info = [list(map(int, input().split())) for i in range(n - 1)] tree = [[] for i in range(n)] for i in range(n - 1): a, b, cost = info[i] tree[a].append((b, cost)) tree[b].append((a, cost)) root = 0 ans = solve(tree, root) for res in ans: print(res) ```
output
1
103,652
13
207,305
Provide a correct Python 3 solution for this coding contest problem. Given a tree T with non-negative weight, find the height of each node of the tree. For each node, the height is the distance to the most distant leaf from the node. Constraints * 1 ≤ n ≤ 10,000 * 0 ≤ wi ≤ 1,000 Input n s1 t1 w1 s2 t2 w2 : sn-1 tn-1 wn-1 The first line consists of an integer n which represents the number of nodes in the tree. Every node has a unique ID from 0 to n-1 respectively. In the following n-1 lines, edges of the tree are given. si and ti represent end-points of the i-th edge (undirected) and wi represents the weight (distance) of the i-th edge. Output The output consists of n lines. Print the height of each node 0, 1, 2, ..., n-1 in order. Example Input 4 0 1 2 1 2 1 1 3 3 Output 5 3 4 5
instruction
0
103,653
13
207,306
"Correct Solution: ``` def tree_height(T, w): N = len(T) # Consider T to be rooted at r = 0 downward = [0] * N # the height of the subtree rooted at each v upward = [-1] * N # the height of the subtree which contains the root r and is rooted at each v height = [-1] * N def dfs1(r): nonlocal downward stack = [(r, -1, 0)] # (vertex, parent, status) while stack: v, p, st = stack.pop() if st == 0: # visited v for the first time n_children = 0 for u in T[v]: if u == p: continue if n_children == 0: stack += [(v, p, 2), (u, v, 0)] n_children += 1 else: stack += [(v, p, 1), (u, v, 0)] n_children += 1 if n_children == 0: # v is a leaf if p != -1: downward[p] = max(downward[p], downward[v] + w[p][v]) elif st == 1: # now searching continue else: # search finished if p != -1: downward[p] = max(downward[p], downward[v] + w[p][v]) def dfs2(r): nonlocal upward, height stack = [(r, -1, 0)] # (vertex, parent, status) while stack: v, p, st = stack.pop() if p == -1: upward[v] = 0 height[v] = max(upward[v], downward[v]) if st == 0: # visited v for the first time max1, max2 = sorted([0, -1] + [downward[child] + w[child][v] for child in T[v] if child != p], reverse=True)[:2] n_children = 0 for u in T[v]: if u == p: continue temp = max1 if downward[u] + w[u][v] == max1: temp = max2 if n_children == 0: stack += [(v, p, 2), (u, v, 0)] upward[u] = max(upward[v], temp) + w[u][v] height[u] = max(upward[u], downward[u]) n_children += 1 else: stack += [(v, p, 1), (u, v, 0)] upward[u] = max(upward[v], temp) + w[u][v] height[u] = max(upward[u], downward[u]) n_children += 1 if n_children == 0: continue elif st == 1: # now searching continue else: # search finished continue dfs1(0) dfs2(0) return height N = int(input()) E = [[] for _ in range(N)] weight = [{} for _ in range(N)] for _ in range(N-1): s, t, w = map(int, input().split()) E[s].append(t); E[t].append(s) weight[s].setdefault(t, w); weight[t].setdefault(s, w) height = tree_height(E, weight) print(*height, sep='\n') ```
output
1
103,653
13
207,307
Provide a correct Python 3 solution for this coding contest problem. Given a tree T with non-negative weight, find the height of each node of the tree. For each node, the height is the distance to the most distant leaf from the node. Constraints * 1 ≤ n ≤ 10,000 * 0 ≤ wi ≤ 1,000 Input n s1 t1 w1 s2 t2 w2 : sn-1 tn-1 wn-1 The first line consists of an integer n which represents the number of nodes in the tree. Every node has a unique ID from 0 to n-1 respectively. In the following n-1 lines, edges of the tree are given. si and ti represent end-points of the i-th edge (undirected) and wi represents the weight (distance) of the i-th edge. Output The output consists of n lines. Print the height of each node 0, 1, 2, ..., n-1 in order. Example Input 4 0 1 2 1 2 1 1 3 3 Output 5 3 4 5
instruction
0
103,654
13
207,308
"Correct Solution: ``` import sys sys.setrecursionlimit(int(1e7)) n = int(input()) tree = {} for i in range(n - 1): s, t, w = map(int, input().split()) if s not in tree: tree[s] = {} if t not in tree: tree[t] = {} tree[s][t] = tree[t][s] = w max_cost = 0 max_id = 0 def visit(v: int, p: int, costs: list): global max_cost, max_id if v not in tree: return for t, w in tree[v].items(): if t == p: continue costs[t] = costs[v] + w if costs[t] >= max_cost: max_cost = costs[t] max_id = t visit(t, v, costs) costs0 = [0] * n costs1 = [0] * n costs2 = [0] * n visit(0, -1, costs0) visit(max_id, -1, costs1) visit(max_id, -1, costs2) for i in range(n): print(max(costs1[i], costs2[i])) ```
output
1
103,654
13
207,309
Provide a correct Python 3 solution for this coding contest problem. Given a tree T with non-negative weight, find the height of each node of the tree. For each node, the height is the distance to the most distant leaf from the node. Constraints * 1 ≤ n ≤ 10,000 * 0 ≤ wi ≤ 1,000 Input n s1 t1 w1 s2 t2 w2 : sn-1 tn-1 wn-1 The first line consists of an integer n which represents the number of nodes in the tree. Every node has a unique ID from 0 to n-1 respectively. In the following n-1 lines, edges of the tree are given. si and ti represent end-points of the i-th edge (undirected) and wi represents the weight (distance) of the i-th edge. Output The output consists of n lines. Print the height of each node 0, 1, 2, ..., n-1 in order. Example Input 4 0 1 2 1 2 1 1 3 3 Output 5 3 4 5
instruction
0
103,655
13
207,310
"Correct Solution: ``` import sys from operator import itemgetter sys.setrecursionlimit(200000) def dfs(u, prev): global post_order, pre_order pre_order.append((u, prev)) for w, t in edges[u]: if t != prev: dfs(t, u) post_order.append(u) n = int(input()) edges = [set() for _ in range(n)] for _ in range(n - 1): s, t, w = map(int, input().split()) edges[s].add((w, t)) edges[t].add((w, s)) post_order, pre_order = [], [] farthest = [{} for _ in range(n)] height = [0] * n if n > 1: dfs(0, None) for i in post_order: for w, t in edges[i]: farthest[i][t] = w + max((d for tt, d in farthest[t].items() if tt != i), default=0) for i, parent in pre_order: sorted_farthest = sorted(farthest[i].items(), key=itemgetter(1)) max_t, max_d = sorted_farthest.pop() height[i] = max_d for w, t in edges[i]: if t == parent: continue farthest[t][i] = w + ((max_d if t != max_t else sorted_farthest[-1][1]) if sorted_farthest else 0) for h in height: print(h) ```
output
1
103,655
13
207,311
Provide a correct Python 3 solution for this coding contest problem. Given a tree T with non-negative weight, find the height of each node of the tree. For each node, the height is the distance to the most distant leaf from the node. Constraints * 1 ≤ n ≤ 10,000 * 0 ≤ wi ≤ 1,000 Input n s1 t1 w1 s2 t2 w2 : sn-1 tn-1 wn-1 The first line consists of an integer n which represents the number of nodes in the tree. Every node has a unique ID from 0 to n-1 respectively. In the following n-1 lines, edges of the tree are given. si and ti represent end-points of the i-th edge (undirected) and wi represents the weight (distance) of the i-th edge. Output The output consists of n lines. Print the height of each node 0, 1, 2, ..., n-1 in order. Example Input 4 0 1 2 1 2 1 1 3 3 Output 5 3 4 5
instruction
0
103,656
13
207,312
"Correct 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]].append((e[1],e[2])) self.tree[e[1]].append((e[0],e[2])) def setroot(self,root): self.root = root self.parent = [None for _ in range(self.n)] self.parent[root] = -1 self.depth = [None for _ in range(self.n)] self.depth[root] = 0 self.distance = [None for _ in range(self.n)] self.distance[root] = 0 stack = [root] while stack: node = stack.pop() for adj,cost in self.tree[node]: if self.parent[adj] is None: self.parent[adj] = node self.depth[adj] = self.depth[node]+1 self.distance[adj] = self.distance[node]+cost stack.append(adj) def diam(self): u = self.distance.index(max(self.distance)) dist_u = [None for _ in range(N)] dist_u[u] = 0 stack = [u] while stack: node = stack.pop() for adj,cost in self.tree[node]: if dist_u[adj] is None: dist_u[adj] = dist_u[node]+cost stack.append(adj) d = max(dist_u) v = dist_u.index(d) return d,u,v def construct_lca(self): L = (self.n-1).bit_length() self.k_parent = [self.parent] prev = self.parent for k in range(L): array = [0 for _ in range(self.n)] for i in range(self.n): if prev[i] == -1: continue array[i] = prev[prev[i]] self.k_parent.append(array) prev = array def lca(self,u,v): d = self.depth[v]-self.depth[u] if d < 0: u,v,d = v,u,-d for k in self.k_parent: if d & 1: v = k[v] d >>= 1 if u == v: return u for k in reversed(self.k_parent): pu,pv = k[u],k[v] if pu != pv: u,v = pu,pv return self.k_parent[0][u] def dist(self,u,v): l = self.lca(u,v) return self.distance[u]+self.distance[v]-2*self.distance[l] import sys input = sys.stdin.readline N = int(input()) E = [tuple(map(int,input().split())) for _ in range(N-1)] t = Tree(N,E) t.setroot(0) t.construct_lca() d,u,v = t.diam() ans = [] for i in range(N): ans.append(max(t.dist(i,u),t.dist(i,v))) print('\n'.join(map(str,ans))) ```
output
1
103,656
13
207,313
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Given a tree T with non-negative weight, find the height of each node of the tree. For each node, the height is the distance to the most distant leaf from the node. Constraints * 1 ≤ n ≤ 10,000 * 0 ≤ wi ≤ 1,000 Input n s1 t1 w1 s2 t2 w2 : sn-1 tn-1 wn-1 The first line consists of an integer n which represents the number of nodes in the tree. Every node has a unique ID from 0 to n-1 respectively. In the following n-1 lines, edges of the tree are given. si and ti represent end-points of the i-th edge (undirected) and wi represents the weight (distance) of the i-th edge. Output The output consists of n lines. Print the height of each node 0, 1, 2, ..., n-1 in order. Example Input 4 0 1 2 1 2 1 1 3 3 Output 5 3 4 5 Submitted Solution: ``` import sys sys.setrecursionlimit(10**7) def dfs(v,p): deg[v]=len(G[v]) res=0 dp[v]=[0]*deg[v] for i in range(deg[v]): nv,c=G[v][i] if nv==p: pi[v]=i continue dp[v][i]=dfs(nv,v)+c res=max(res,dp[v][i]) return res def reroot(v,res_p,p): if p!=-1: dp[v][pi[v]]=res_p h[v]=max(dp[v]) dpl=[0]*(deg[v]+1) dpr=[0]*(deg[v]+1) for i in range(deg[v]): dpl[i+1]=max(dpl[i],dp[v][i]) for i in reversed(range(deg[v])): dpr[i]=max(dpr[i+1],dp[v][i]) for i in range(deg[v]): nv,c=G[v][i] if nv==p: continue reroot(nv,max(dpl[i],dpr[i+1])+c,v) n=int(input()) G=[[] for i in range(n)] dp=[[] for i in range(n)] deg=[0]*n pi=[-1]*n for i in range(n-1): s,t,w=map(int,input().split()) G[s].append((t,w)) G[t].append((s,w)) z=dfs(0,-1) h=[0]*n h[0]=z reroot(0,0,-1) print(*h,sep='\n') ```
instruction
0
103,657
13
207,314
Yes
output
1
103,657
13
207,315
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Given a tree T with non-negative weight, find the height of each node of the tree. For each node, the height is the distance to the most distant leaf from the node. Constraints * 1 ≤ n ≤ 10,000 * 0 ≤ wi ≤ 1,000 Input n s1 t1 w1 s2 t2 w2 : sn-1 tn-1 wn-1 The first line consists of an integer n which represents the number of nodes in the tree. Every node has a unique ID from 0 to n-1 respectively. In the following n-1 lines, edges of the tree are given. si and ti represent end-points of the i-th edge (undirected) and wi represents the weight (distance) of the i-th edge. Output The output consists of n lines. Print the height of each node 0, 1, 2, ..., n-1 in order. Example Input 4 0 1 2 1 2 1 1 3 3 Output 5 3 4 5 Submitted Solution: ``` from collections import deque def bfs(n, adj, source): dist = [-1] * n dist[source] = 0 q = deque([source]) mx = 0 idx = 0 while q: cur = q.popleft() for nxt, d in adj[cur]: if dist[nxt] < 0: dist[nxt] = dist[cur] + d if dist[nxt] > mx: mx = dist[nxt] idx = nxt q.append(nxt) return idx, mx, dist def main(): n, *L = map(int, open(0).read().split()) adj = [[] for _ in range(n)] for a, b, c in zip(*[iter(L)] * 3): adj[a].append((b, c)) adj[b].append((a, c)) idx1, _, _ = bfs(n, adj, 0) idx2, _, dist1 = bfs(n, adj, idx1) idx3, _, dist2 = bfs(n, adj, idx2) ans = [max(x, y) for x, y in zip(dist1, dist2)] print("\n".join(map(str, ans))) if __name__ == '__main__': main() ```
instruction
0
103,658
13
207,316
Yes
output
1
103,658
13
207,317
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Given a tree T with non-negative weight, find the height of each node of the tree. For each node, the height is the distance to the most distant leaf from the node. Constraints * 1 ≤ n ≤ 10,000 * 0 ≤ wi ≤ 1,000 Input n s1 t1 w1 s2 t2 w2 : sn-1 tn-1 wn-1 The first line consists of an integer n which represents the number of nodes in the tree. Every node has a unique ID from 0 to n-1 respectively. In the following n-1 lines, edges of the tree are given. si and ti represent end-points of the i-th edge (undirected) and wi represents the weight (distance) of the i-th edge. Output The output consists of n lines. Print the height of each node 0, 1, 2, ..., n-1 in order. Example Input 4 0 1 2 1 2 1 1 3 3 Output 5 3 4 5 Submitted Solution: ``` def solve(prev, r, n, dic): d = [0] * n md = 0 t = r stack = [] stack += [[prev, r, 0]] while stack: prev, r, d1 = stack.pop(-1) if r in dic: for vtx, cost in dic[r]: if vtx == prev: continue stack += [[r, vtx, d1 + cost]] if d[vtx] < d1 + cost: d[vtx] = d1 + cost if md < d[vtx]: md = d[vtx] t = vtx return d, t dic = {} line = input() n = int(line) for _ in range(1, n): line = input() s, t, w = list(map(int, line.split())) if s not in dic: dic[s] = [[t, w]] else: dic[s] += [[t, w]] if t not in dic: dic[t] = [[s, w]] else: dic[t] += [[s, w]] d1, t1 = solve(-1, 0, n, dic) d2, t2 = solve(-1, t1, n, dic) d3, t3 = solve(-1, t2, n, dic) print("\n".join(map(str, [max(a, b) for a, b in zip(d2, d3)] ))) ```
instruction
0
103,659
13
207,318
Yes
output
1
103,659
13
207,319
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Given a tree T with non-negative weight, find the height of each node of the tree. For each node, the height is the distance to the most distant leaf from the node. Constraints * 1 ≤ n ≤ 10,000 * 0 ≤ wi ≤ 1,000 Input n s1 t1 w1 s2 t2 w2 : sn-1 tn-1 wn-1 The first line consists of an integer n which represents the number of nodes in the tree. Every node has a unique ID from 0 to n-1 respectively. In the following n-1 lines, edges of the tree are given. si and ti represent end-points of the i-th edge (undirected) and wi represents the weight (distance) of the i-th edge. Output The output consists of n lines. Print the height of each node 0, 1, 2, ..., n-1 in order. Example Input 4 0 1 2 1 2 1 1 3 3 Output 5 3 4 5 Submitted Solution: ``` #!usr/bin/env python3 from collections import defaultdict, deque from heapq import heappush, heappop from itertools import permutations, accumulate import sys import math import bisect def LI(): return [int(x) for x in sys.stdin.readline().split()] def I(): return int(sys.stdin.readline()) def LS():return [list(x) for x in sys.stdin.readline().split()] def S(): res = list(sys.stdin.readline()) if res[-1] == "\n": return res[:-1] return res def IR(n): return [I() for i in range(n)] def LIR(n): return [LI() for i in range(n)] def SR(n): return [S() for i in range(n)] def LSR(n): return [LS() for i in range(n)] sys.setrecursionlimit(1000000) mod = 1000000007 def solve(): fl = defaultdict(lambda : 0) fr = defaultdict(lambda : 0) def dfs(x,hx): p = 0 for y,c in v[x]: if hx < h[y]: continue fl[(x,y)] = p nh = h[y]+c if p < nh: p = nh p = 0 for y,c in v[x][::-1]: if hx < h[y]: continue fr[(x,y)] = p nh = h[y]+c if p < nh: p = nh for y,c in v[x]: hy = h[y] if hx < hy: continue if ans[y]:continue nhx = max(fl[(x,y)],fr[(x,y)]) ans[y] = nhy = max(h[y],nhx+c) h[x] = nhx dfs(y,nhy) h[x] = hx n = I() v = [[] for i in range(n)] for i in range(n-1): a,b,c = LI() v[a].append((b,c)) v[b].append((a,c)) q = [0] q2 = [] h = [-1]*n h[0] = 0 while q: x = q.pop() for y,c in v[x]: if h[y] < 0: h[y] = 0 q.append(y) q2.append((y,x,c)) while q2: y,x,c = q2.pop() nh = h[y]+c if h[x] < nh: h[x] = nh ans = [0]*n ans[0] = h[0] dfs(0,h[0]) for i in ans: print(i) return #Solve if __name__ == "__main__": solve() ```
instruction
0
103,660
13
207,320
Yes
output
1
103,660
13
207,321
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Given a tree T with non-negative weight, find the height of each node of the tree. For each node, the height is the distance to the most distant leaf from the node. Constraints * 1 ≤ n ≤ 10,000 * 0 ≤ wi ≤ 1,000 Input n s1 t1 w1 s2 t2 w2 : sn-1 tn-1 wn-1 The first line consists of an integer n which represents the number of nodes in the tree. Every node has a unique ID from 0 to n-1 respectively. In the following n-1 lines, edges of the tree are given. si and ti represent end-points of the i-th edge (undirected) and wi represents the weight (distance) of the i-th edge. Output The output consists of n lines. Print the height of each node 0, 1, 2, ..., n-1 in order. Example Input 4 0 1 2 1 2 1 1 3 3 Output 5 3 4 5 Submitted Solution: ``` def solve(prev, r, n, dic): d = [0] * n md = 0 t = r stack = [] stack += [[prev, r, 0]] while stack: prev, r, d1 = stack.pop(-1) if r in dic: for vtx, cost in dic[r]: if vtx == prev: continue stack += [[r, vtx, d1 + cost]] if d[vtx] < d1 + cost: d[vtx] = d1 + cost if md < d[vtx]: md = d[vtx] t = vtx return d, t dic = {} line = input() n = int(line) for _ in range(1, n): line = input() s, t, w = list(map(int, line.split())) if s not in dic: dic[s] = [[t, w]] else: dic[s] += [[t, w]] if t not in dic: dic[t] = [[s, w]] else: dic[t] += [[s, w]] d1, t1 = solve(-1, 0, n, dic) d2, t2 = solve(-1, t1, n, dic) d2[t1] = d2[t2] print("\n".join(map(str,d2))) ```
instruction
0
103,661
13
207,322
No
output
1
103,661
13
207,323
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Given a tree T with non-negative weight, find the height of each node of the tree. For each node, the height is the distance to the most distant leaf from the node. Constraints * 1 ≤ n ≤ 10,000 * 0 ≤ wi ≤ 1,000 Input n s1 t1 w1 s2 t2 w2 : sn-1 tn-1 wn-1 The first line consists of an integer n which represents the number of nodes in the tree. Every node has a unique ID from 0 to n-1 respectively. In the following n-1 lines, edges of the tree are given. si and ti represent end-points of the i-th edge (undirected) and wi represents the weight (distance) of the i-th edge. Output The output consists of n lines. Print the height of each node 0, 1, 2, ..., n-1 in order. Example Input 4 0 1 2 1 2 1 1 3 3 Output 5 3 4 5 Submitted Solution: ``` from sys import stdin from collections import defaultdict readline = stdin.readline def main(): n = int(readline()) g = defaultdict(list) for _ in range(n - 1): s, t, d = map(int, readline().split()) g[s].append([d, t]) dp = defaultdict(dict) for i in postorder(g): if len(g[i]) == 0: continue for di, ti in g[i]: dp[i][ti] = di if g[ti]: dp[i][ti] += max(d for d, t in g[ti]) height = [None] * n for i in preorder(g): height[i] = max(dp[i].values()) for d, t in g[i]: dp[t][i] = d if 1 < len(dp[i]): dp[t][i] += max(v for k, v in dp[i].items() if k != t) print('\n'.join(map(str, height))) def preorder(g): dfs_stack = [0] while dfs_stack: u = dfs_stack.pop() yield(u) dfs_stack.extend(t for d, t in g[u]) def postorder(g): parent_stack = [] dfs_stack = [(0, None)] while dfs_stack: u, prev = dfs_stack.pop() dfs_stack.extend((t, u) for d, t in g[u]) while parent_stack and parent_stack[-1] != prev: yield parent_stack.pop() parent_stack.append(u) while parent_stack: yield parent_stack.pop() main() ```
instruction
0
103,662
13
207,324
No
output
1
103,662
13
207,325
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Given a tree T with non-negative weight, find the height of each node of the tree. For each node, the height is the distance to the most distant leaf from the node. Constraints * 1 ≤ n ≤ 10,000 * 0 ≤ wi ≤ 1,000 Input n s1 t1 w1 s2 t2 w2 : sn-1 tn-1 wn-1 The first line consists of an integer n which represents the number of nodes in the tree. Every node has a unique ID from 0 to n-1 respectively. In the following n-1 lines, edges of the tree are given. si and ti represent end-points of the i-th edge (undirected) and wi represents the weight (distance) of the i-th edge. Output The output consists of n lines. Print the height of each node 0, 1, 2, ..., n-1 in order. Example Input 4 0 1 2 1 2 1 1 3 3 Output 5 3 4 5 Submitted Solution: ``` from sys import stdin from collections import defaultdict readline = stdin.readline def main(): n = int(readline()) g = defaultdict(list) for _ in range(n - 1): s, t, d = map(int, readline().split()) g[s].append([d, t]) dp = defaultdict(dict) r = root(g) for i in postorder(g, r): if len(g[i]) == 0: continue for di, ti in g[i]: dp[i][ti] = di if g[ti]: dp[i][ti] += max(dp[ti].values()) height = [None] * n for i in preorder(g, r): height[i] = max(dp[i].values()) if dp[i] else 0 for d, t in g[i]: dp[t][i] = d if 1 < len(dp[i]): dp[t][i] += max(v for k, v in dp[i].items() if k != t) print('\n'.join(map(str, height))) def root(g): return set(g.keys()).difference({t for x in g.values() for d, t in x}).pop() if g else 0 def preorder(g, r): dfs_stack = [r] while dfs_stack: u = dfs_stack.pop() yield(u) dfs_stack.extend(t for d, t in g[u]) def postorder(g, r): parent_stack = [] dfs_stack = [(r, None)] while dfs_stack: u, prev = dfs_stack.pop() dfs_stack.extend((t, u) for d, t in g[u]) while parent_stack and parent_stack[-1] != prev: yield parent_stack.pop() parent_stack.append(u) while parent_stack: yield parent_stack.pop() main() ```
instruction
0
103,663
13
207,326
No
output
1
103,663
13
207,327
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Given a tree T with non-negative weight, find the height of each node of the tree. For each node, the height is the distance to the most distant leaf from the node. Constraints * 1 ≤ n ≤ 10,000 * 0 ≤ wi ≤ 1,000 Input n s1 t1 w1 s2 t2 w2 : sn-1 tn-1 wn-1 The first line consists of an integer n which represents the number of nodes in the tree. Every node has a unique ID from 0 to n-1 respectively. In the following n-1 lines, edges of the tree are given. si and ti represent end-points of the i-th edge (undirected) and wi represents the weight (distance) of the i-th edge. Output The output consists of n lines. Print the height of each node 0, 1, 2, ..., n-1 in order. Example Input 4 0 1 2 1 2 1 1 3 3 Output 5 3 4 5 Submitted Solution: ``` #!/usr/bin/env python3 # GRL_5_B: Tree - Height of a Tree import bisect class Edge: __slots__ = ('v', 'w') def __init__(self, v, w): self.v = v self.w = w def either(self): return self.v def other(self, v): if v == self.v: return self.w else: return self.v class WeightedEdge(Edge): __slots__ = ('v', 'w', 'weight') def __init__(self, v, w, weight): super().__init__(v, w) self.weight = weight class Graph: def __init__(self, v): self.v = v self._edges = [[] for _ in range(v)] def add(self, e): self._edges[e.v].append(e) self._edges[e.w].append(e) def adj(self, v): return self._edges[v] def edges(self): for es in self._edges: for e in es: yield e def heights(graph): s = 0 edge_to = [None] * graph.v dists = [[(0, i)] for i in range(graph.v)] stack = [s] while stack: v = stack.pop() for e in graph.adj(v): if e != edge_to[v]: w = e.other(v) if edge_to[w] is None: edge_to[w] = e stack.append(v) stack.append(w) break else: for e in graph.adj(v): if e != edge_to[v]: w = e.other(v) bisect.insort(dists[v], (dists[w][-1][0] + e.weight, w)) hs = [d[-1][0] for d in dists] for i in range(graph.v): j = i weight = 0 while j != s: e = edge_to[j] weight += e.weight w = e.other(j) for vw, v in dists[w]: if v != j and weight + vw > hs[i]: hs[i] = weight + vw j = w return hs def run(): n = int(input()) g = Graph(n) for _ in range(n-1): s, t, w = [int(i) for i in input().split()] g.add(WeightedEdge(s, t, w)) for w in heights(g): print(w) if __name__ == '__main__': run() ```
instruction
0
103,664
13
207,328
No
output
1
103,664
13
207,329
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an undirected graph where each edge has one of two colors: black or red. Your task is to assign a real number to each node so that: * for each black edge the sum of values at its endpoints is 1; * for each red edge the sum of values at its endpoints is 2; * the sum of the absolute values of all assigned numbers is the smallest possible. Otherwise, if it is not possible, report that there is no feasible assignment of the numbers. Input The first line contains two integers N (1 ≤ N ≤ 100 000) and M (0 ≤ M ≤ 200 000): the number of nodes and the number of edges, respectively. The nodes are numbered by consecutive integers: 1, 2, …, N. The next M lines describe the edges. Each line contains three integers a, b and c denoting that there is an edge between nodes a and b (1 ≤ a, b ≤ N) with color c (1 denotes black, 2 denotes red). Output If there is a solution, the first line should contain the word "YES" and the second line should contain N space-separated numbers. For each i (1 ≤ i ≤ N), the i-th number should be the number assigned to the node i. Output should be such that: * the sum of the numbers at the endpoints of each edge differs from the precise value by less than 10^{-6}; * the sum of the absolute values of all assigned numbers differs from the smallest possible by less than 10^{-6}. If there are several valid solutions, output any of them. If there is no solution, the only line should contain the word "NO". Scoring Subtasks: 1. (5 points) N ≤ 5, M ≤ 14 2. (12 points) N ≤ 100 3. (17 points) N ≤ 1000 4. (24 points) N ≤ 10 000 5. (42 points) No further constraints Examples Input 4 4 1 2 1 2 3 2 1 3 2 3 4 1 Output YES 0.5 0.5 1.5 -0.5 Input 2 1 1 2 1 Output YES 0.3 0.7 Input 3 2 1 2 2 2 3 2 Output YES 0 2 0 Input 3 4 1 2 2 2 2 1 2 1 1 1 2 2 Output NO Note Note that in the second example the solution is not unique.
instruction
0
103,865
13
207,730
Tags: *special, binary search, dfs and similar, dp, math, ternary search Correct Solution: ``` # SOLUTION CREDITS: https://codeforces.com/profile/TheVan import os import sys from io import BytesIO, IOBase # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline() # ------------------------------ def RL(): return map(int, sys.stdin.readline().split()) def RLL(): return list(map(int, sys.stdin.readline().split())) def N(): return int(input()) def print_list(l): print(' '.join(map(str,l))) # import heapq as hq # import bisect as bs # from collections import deque as dq # from collections import defaultdict as dc # from math import ceil,floor,sqrt # from collections import Counter n,m = RL() dic = [[] for _ in range(n+1)] for _ in range(m): u,v,t = RL() dic[u].append((v,t)) dic[v].append((u,t)) v = [None] * (n+1) f = [True] * (n+1) key = {} color = [0]*(n+1) flag = True for s in range(1,n+1): if v[s] is not None: continue v[s] = 0 color[s] = s now = [s] ss = [0] while now and flag: p = now.pop() for child,t in dic[p]: if v[child] is not None: if f[child]!=f[p]: if v[child]+v[p]!=t: flag = False break elif f[child] is True: if s not in key: key[s] = (v[child]+v[p]-t)/(-2) elif v[child]+v[p]+key[s]*2!=t: flag = False break else: if s not in key: key[s] = (v[child]+v[p]-t)/2 elif v[child]+v[p]-key[s]*2!=t: flag = False break else: v[child] = t-v[p] f[child] = not f[p] if f[child]: ss.append(-1*v[child]) else: ss.append(v[child]) color[child] = s now.append(child) if not flag: break if s not in key: ss.sort() nn = len(ss) key[s] = (ss[nn>>1]+ss[nn-1>>1])/2 if flag: print("YES") res = [] for i in range(1,n+1): if f[i]: res.append(v[i]+key[color[i]]) else: res.append(v[i]-key[color[i]]) print_list(res) else: print("NO") '''import os import sys from io import BytesIO, IOBase # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline() # ------------------------------ def RL(): return map(int, sys.stdin.readline().split()) def RLL(): return list(map(int, sys.stdin.readline().split())) def N(): return int(input()) def print_list(l): print(' '.join(map(str,l)))''' ''' import heapq as hq import bisect as bs from collections import deque as dq from collections import defaultdict as dc from math import ceil, floor, sqrt from collections import Counter n, m = map(int, input().split()) dic = [[] for _ in range(n + 1)] for _ in range(m): u, v, t = map(int, input().split()) dic[u].append((v, t)) dic[v].append((u, t)) v = [None for _ in range(n + 1)] f = [True for _ in range(n + 1)] key = {} color = [0 for _ in range(n + 1)] flag = True for s in range(1, n + 1): if v[s]: continue v[s] = 0 color[s] = s now = [s] ss = [0] while now and flag: p = now.pop() for child,t in dic[p]: if v[child]: if f[child] != f[p]: if v[child] + v[p] != t: flag = False break elif f[child]: if s not in key: key[s] = (v[child] + v[p] - t) / (-2) elif v[child] + v[p] + key[s] * 2 != t: flag = False break else: if s not in key: key[s] = (v[child] + v[p] - t) / 2 elif v[child] + v[p] - key[s] * 2 != t: flag = False break else: v[child] = t - v[p] f[child] = not f[p] if f[child]: ss.append(-v[child]) else: ss.append(v[child]) color[child] = s now.append(child) if not flag: break if s not in key: ss.sort() nn = len(ss) key[s] = (ss[nn >> 1] + ss[nn - 1 >> 1]) / 2 if flag: print("YES") res = [] for i in range(1, n + 1): if f[i]: res.append(v[i] + key[color[i]]) else: res.append(v[i] - key[color[i]]) print(' '.join(map(str, res))) else: print("NO")''' ```
output
1
103,865
13
207,731
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an undirected graph where each edge has one of two colors: black or red. Your task is to assign a real number to each node so that: * for each black edge the sum of values at its endpoints is 1; * for each red edge the sum of values at its endpoints is 2; * the sum of the absolute values of all assigned numbers is the smallest possible. Otherwise, if it is not possible, report that there is no feasible assignment of the numbers. Input The first line contains two integers N (1 ≤ N ≤ 100 000) and M (0 ≤ M ≤ 200 000): the number of nodes and the number of edges, respectively. The nodes are numbered by consecutive integers: 1, 2, …, N. The next M lines describe the edges. Each line contains three integers a, b and c denoting that there is an edge between nodes a and b (1 ≤ a, b ≤ N) with color c (1 denotes black, 2 denotes red). Output If there is a solution, the first line should contain the word "YES" and the second line should contain N space-separated numbers. For each i (1 ≤ i ≤ N), the i-th number should be the number assigned to the node i. Output should be such that: * the sum of the numbers at the endpoints of each edge differs from the precise value by less than 10^{-6}; * the sum of the absolute values of all assigned numbers differs from the smallest possible by less than 10^{-6}. If there are several valid solutions, output any of them. If there is no solution, the only line should contain the word "NO". Scoring Subtasks: 1. (5 points) N ≤ 5, M ≤ 14 2. (12 points) N ≤ 100 3. (17 points) N ≤ 1000 4. (24 points) N ≤ 10 000 5. (42 points) No further constraints Examples Input 4 4 1 2 1 2 3 2 1 3 2 3 4 1 Output YES 0.5 0.5 1.5 -0.5 Input 2 1 1 2 1 Output YES 0.3 0.7 Input 3 2 1 2 2 2 3 2 Output YES 0 2 0 Input 3 4 1 2 2 2 2 1 2 1 1 1 2 2 Output NO Note Note that in the second example the solution is not unique.
instruction
0
103,866
13
207,732
Tags: *special, binary search, dfs and similar, dp, math, ternary search Correct Solution: ``` import os import sys from io import BytesIO, IOBase # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline() # ------------------------------ def RL(): return map(int, sys.stdin.readline().split()) def RLL(): return list(map(int, sys.stdin.readline().split())) def N(): return int(input()) def print_list(l): print(' '.join(map(str,l))) # import heapq as hq # import bisect as bs # from collections import deque as dq # from collections import defaultdict as dc # from math import ceil,floor,sqrt # from collections import Counter n,m = RL() dic = [[] for _ in range(n+1)] for _ in range(m): u,v,t = RL() dic[u].append((v,t)) dic[v].append((u,t)) v = [None] * (n+1) f = [True] * (n+1) key = {} color = [0]*(n+1) flag = True for s in range(1,n+1): if v[s] is not None: continue v[s] = 0 color[s] = s now = [s] ss = [0] while now and flag: p = now.pop() for child,t in dic[p]: if v[child] is not None: if f[child]!=f[p]: if v[child]+v[p]!=t: flag = False break elif f[child] is True: if s not in key: key[s] = (v[child]+v[p]-t)/(-2) elif v[child]+v[p]+key[s]*2!=t: flag = False break else: if s not in key: key[s] = (v[child]+v[p]-t)/2 elif v[child]+v[p]-key[s]*2!=t: flag = False break else: v[child] = t-v[p] f[child] = not f[p] if f[child]: ss.append(-1*v[child]) else: ss.append(v[child]) color[child] = s now.append(child) if not flag: break if s not in key: ss.sort() nn = len(ss) key[s] = (ss[nn>>1]+ss[nn-1>>1])/2 if flag: print("YES") res = [] for i in range(1,n+1): if f[i]: res.append(v[i]+key[color[i]]) else: res.append(v[i]-key[color[i]]) print_list(res) else: print("NO") ```
output
1
103,866
13
207,733
Provide tags and a correct Python 3 solution for this coding contest problem. In this problem at each moment you have a set of intervals. You can move from interval (a, b) from our set to interval (c, d) from our set if and only if c < a < d or c < b < d. Also there is a path from interval I1 from our set to interval I2 from our set if there is a sequence of successive moves starting from I1 so that we can reach I2. Your program should handle the queries of the following two types: 1. "1 x y" (x < y) — add the new interval (x, y) to the set of intervals. The length of the new interval is guaranteed to be strictly greater than all the previous intervals. 2. "2 a b" (a ≠ b) — answer the question: is there a path from a-th (one-based) added interval to b-th (one-based) added interval? Answer all the queries. Note, that initially you have an empty set of intervals. Input The first line of the input contains integer n denoting the number of queries, (1 ≤ n ≤ 105). Each of the following lines contains a query as described above. All numbers in the input are integers and don't exceed 109 by their absolute value. It's guaranteed that all queries are correct. Output For each query of the second type print "YES" or "NO" on a separate line depending on the answer. Examples Input 5 1 1 5 1 5 11 2 1 2 1 2 9 2 1 2 Output NO YES
instruction
0
103,988
13
207,976
Tags: data structures Correct Solution: ``` def dfs(node, destination): if node == destination: return True visited[node] = True for adj in graph[node]: if not visited[adj] and dfs(adj, destination): return True return False n = int(input()) graph = [[] for _ in range(n+1)] intervals = [] for _ in range(n): t, first, second = map(int, input().split()) if t == 1: no = len(intervals) for interval in intervals: if interval[0] < first < interval[1] or interval[0] < second < interval[1]: graph[no].append(interval[2]) if first < interval[0] < second or first < interval[1] < second: graph[interval[2]].append(no) intervals.append((first, second, no)) else: visited = [False] * (n + 1) print("YES" if dfs(first-1, second-1) else "NO") ```
output
1
103,988
13
207,977
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. In this problem at each moment you have a set of intervals. You can move from interval (a, b) from our set to interval (c, d) from our set if and only if c < a < d or c < b < d. Also there is a path from interval I1 from our set to interval I2 from our set if there is a sequence of successive moves starting from I1 so that we can reach I2. Your program should handle the queries of the following two types: 1. "1 x y" (x < y) — add the new interval (x, y) to the set of intervals. The length of the new interval is guaranteed to be strictly greater than all the previous intervals. 2. "2 a b" (a ≠ b) — answer the question: is there a path from a-th (one-based) added interval to b-th (one-based) added interval? Answer all the queries. Note, that initially you have an empty set of intervals. Input The first line of the input contains integer n denoting the number of queries, (1 ≤ n ≤ 105). Each of the following lines contains a query as described above. All numbers in the input are integers and don't exceed 109 by their absolute value. It's guaranteed that all queries are correct. Output For each query of the second type print "YES" or "NO" on a separate line depending on the answer. Examples Input 5 1 1 5 1 5 11 2 1 2 1 2 9 2 1 2 Output NO YES Submitted Solution: ``` import collections def update_edges(intervals, edges, new_interval): new_interval_id = len(intervals) for idx, interval in enumerate(intervals): # connect from new -> old if interval[0] < new_interval[0] < interval[1] or interval[0] < new_interval[1] < interval[1]: edges[new_interval_id].append(idx) # connect from old -> new if new_interval[0] < interval[0] < new_interval[1] or new_interval[0] < interval[1] < new_interval[1]: edges[idx].append(new_interval_id) def bfs(edges, start, target): seen = set() q = collections.deque([start]) while len(q) != 0: v = q.popleft() if v in seen: continue if v == target: return "YES" seen.add(v) for nb in edges[v]: q.append(nb) return "NO" def main(): queries = int(input()) edges = collections.defaultdict(list) intervals = [] for _ in range(queries): query, a, b = map(int, input().split(' ')) if query == 1: new_interval = (a, b) update_edges(intervals, edges, new_interval) intervals.append(new_interval) if query == 2: print(bfs(edges, a-1, b-1)) if __name__ == "__main__": main() ```
instruction
0
103,991
13
207,982
Yes
output
1
103,991
13
207,983
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. In this problem you will have to deal with a very special network. The network consists of two parts: part A and part B. Each part consists of n vertices; i-th vertex of part A is denoted as Ai, and i-th vertex of part B is denoted as Bi. For each index i (1 ≤ i < n) there is a directed edge from vertex Ai to vertex Ai + 1, and from Bi to Bi + 1, respectively. Capacities of these edges are given in the input. Also there might be several directed edges going from part A to part B (but never from B to A). You have to calculate the [maximum flow value](https://en.wikipedia.org/wiki/Maximum_flow_problem) from A1 to Bn in this network. Capacities of edges connecting Ai to Ai + 1 might sometimes change, and you also have to maintain the maximum flow value after these changes. Apart from that, the network is fixed (there are no changes in part B, no changes of edges going from A to B, and no edge insertions or deletions). Take a look at the example and the notes to understand the structure of the network better. Input The first line contains three integer numbers n, m and q (2 ≤ n, m ≤ 2·105, 0 ≤ q ≤ 2·105) — the number of vertices in each part, the number of edges going from A to B and the number of changes, respectively. Then n - 1 lines follow, i-th line contains two integers xi and yi denoting that the edge from Ai to Ai + 1 has capacity xi and the edge from Bi to Bi + 1 has capacity yi (1 ≤ xi, yi ≤ 109). Then m lines follow, describing the edges from A to B. Each line contains three integers x, y and z denoting an edge from Ax to By with capacity z (1 ≤ x, y ≤ n, 1 ≤ z ≤ 109). There might be multiple edges from Ax to By. And then q lines follow, describing a sequence of changes to the network. i-th line contains two integers vi and wi, denoting that the capacity of the edge from Avi to Avi + 1 is set to wi (1 ≤ vi < n, 1 ≤ wi ≤ 109). Output Firstly, print the maximum flow value in the original network. Then print q integers, i-th of them must be equal to the maximum flow value after i-th change. Example Input 4 3 2 1 2 3 4 5 6 2 2 7 1 4 8 4 3 9 1 100 2 100 Output 9 14 14 Note This is the original network in the example: <image> Submitted Solution: ``` print("9\n14\n14") ```
instruction
0
104,150
13
208,300
No
output
1
104,150
13
208,301
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. In this problem you will have to deal with a very special network. The network consists of two parts: part A and part B. Each part consists of n vertices; i-th vertex of part A is denoted as Ai, and i-th vertex of part B is denoted as Bi. For each index i (1 ≤ i < n) there is a directed edge from vertex Ai to vertex Ai + 1, and from Bi to Bi + 1, respectively. Capacities of these edges are given in the input. Also there might be several directed edges going from part A to part B (but never from B to A). You have to calculate the [maximum flow value](https://en.wikipedia.org/wiki/Maximum_flow_problem) from A1 to Bn in this network. Capacities of edges connecting Ai to Ai + 1 might sometimes change, and you also have to maintain the maximum flow value after these changes. Apart from that, the network is fixed (there are no changes in part B, no changes of edges going from A to B, and no edge insertions or deletions). Take a look at the example and the notes to understand the structure of the network better. Input The first line contains three integer numbers n, m and q (2 ≤ n, m ≤ 2·105, 0 ≤ q ≤ 2·105) — the number of vertices in each part, the number of edges going from A to B and the number of changes, respectively. Then n - 1 lines follow, i-th line contains two integers xi and yi denoting that the edge from Ai to Ai + 1 has capacity xi and the edge from Bi to Bi + 1 has capacity yi (1 ≤ xi, yi ≤ 109). Then m lines follow, describing the edges from A to B. Each line contains three integers x, y and z denoting an edge from Ax to By with capacity z (1 ≤ x, y ≤ n, 1 ≤ z ≤ 109). There might be multiple edges from Ax to By. And then q lines follow, describing a sequence of changes to the network. i-th line contains two integers vi and wi, denoting that the capacity of the edge from Avi to Avi + 1 is set to wi (1 ≤ vi < n, 1 ≤ wi ≤ 109). Output Firstly, print the maximum flow value in the original network. Then print q integers, i-th of them must be equal to the maximum flow value after i-th change. Example Input 4 3 2 1 2 3 4 5 6 2 2 7 1 4 8 4 3 9 1 100 2 100 Output 9 14 14 Note This is the original network in the example: <image> Submitted Solution: ``` aList = [123, 'xyz', 'zara', 'abc']; print("Length of aList: ",len(aList)) while aList: print(aList.pop()) print("Length of aList: ",len(aList)) ```
instruction
0
104,151
13
208,302
No
output
1
104,151
13
208,303
Provide a correct Python 3 solution for this coding contest problem. problem AOR Ika likes rooted trees with a fractal (self-similar) structure. Consider using the weighted rooted tree $ T $ consisting of $ N $ vertices to represent the rooted tree $ T'$ with the following fractal structure. * $ T'$ is the addition of a tree rooted at $ x $ and having a tree structure similar to $ T $ (same cost) for each vertex $ x $ of $ T $. * The root of $ T'$ is the same as that of $ T $. The tree represented in this way is, for example, as shown in the figure below. <image> AOR Ika is trying to do a depth-first search for $ T'$, but finds that it takes a lot of time to trace all the vertices. Therefore, we decided to skip some node visits by performing a depth-first search with a policy of transitioning with a probability of $ p $ and not transitioning with a probability of $ 1-p $ at the time of transition during a depth-first search. Given $ T $ and the probability $ p $, find the expected value of the sum of the costs of all edges to follow when performing a depth-first search for $ T'$. The information of $ T $ is given by the number of vertices $ N $ and the information of the edges of $ N-1 $, and the vertex $ 1 $ is the root. Each vertex is labeled $ 1,2, \ dots, N $, and the $ i \ (1 \ le i \ le N-1) $ th edge costs the vertices $ x_i $ and $ y_i $ $ c_i $ It is tied with. The non-deterministic algorithm of the depth-first search that transitions to a child with a probability of $ p $, which is dealt with in this problem, is expressed as follows. The sum of the costs of the edges that the output $ \ mathrm {answer} $ follows. 1. Prepare an empty stack $ S $. 2. Set $ ​​\ mathrm {answer} = 0 $ 3. Push the root vertex of $ T'$ to $ S $. 4. Extract the first element of $ S $ and make it $ x $. 5. For each child $ c $ of $ x $, do the following with probability $ p $ and do nothing with probability $ 1-p $. * Add vertex $ c $ to $ S $. Then add the weight of the edge connecting $ x $ to $ c $ to $ \ mathrm {answer} $. 6. If S is not empty, transition to 3. 7. Output $ \ mathrm {answer} $. output Print the answer in one line. If the relative or absolute error is less than $ 10 ^ {-6} $, then AC. Also, output a line break at the end. Example Input 0.75 4 1 2 1 2 3 3 3 4 10 Output 24.8569335938
instruction
0
104,385
13
208,770
"Correct Solution: ``` import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time sys.setrecursionlimit(10**7) inf = 10**20 mod = 10**9 + 7 def LI(): return list(map(int, input().split())) def LF(): return list(map(float, input().split())) def LS(): return input().split() def I(): return int(input()) def F(): return float(input()) def S(): return input() def main(): p = F() n = I() d = collections.defaultdict(list) for _ in range(n-1): x,y,c = LI() d[x-1].append((y-1,c)) d[y-1].append((x-1,c)) f = [None] * n f[0] = (0,0) q = [(0,0)] while q: x,b = q[0] q = q[1:] for y,c in d[x]: if f[y]: continue q.append((y,b+1)) f[y] = (b+1, c) s = 0 for b,c in f: s += p**b * c r = s for b,c in f: r += p**b * s return r print(main()) ```
output
1
104,385
13
208,771
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. problem AOR Ika likes rooted trees with a fractal (self-similar) structure. Consider using the weighted rooted tree $ T $ consisting of $ N $ vertices to represent the rooted tree $ T'$ with the following fractal structure. * $ T'$ is the addition of a tree rooted at $ x $ and having a tree structure similar to $ T $ (same cost) for each vertex $ x $ of $ T $. * The root of $ T'$ is the same as that of $ T $. The tree represented in this way is, for example, as shown in the figure below. <image> AOR Ika is trying to do a depth-first search for $ T'$, but finds that it takes a lot of time to trace all the vertices. Therefore, we decided to skip some node visits by performing a depth-first search with a policy of transitioning with a probability of $ p $ and not transitioning with a probability of $ 1-p $ at the time of transition during a depth-first search. Given $ T $ and the probability $ p $, find the expected value of the sum of the costs of all edges to follow when performing a depth-first search for $ T'$. The information of $ T $ is given by the number of vertices $ N $ and the information of the edges of $ N-1 $, and the vertex $ 1 $ is the root. Each vertex is labeled $ 1,2, \ dots, N $, and the $ i \ (1 \ le i \ le N-1) $ th edge costs the vertices $ x_i $ and $ y_i $ $ c_i $ It is tied with. The non-deterministic algorithm of the depth-first search that transitions to a child with a probability of $ p $, which is dealt with in this problem, is expressed as follows. The sum of the costs of the edges that the output $ \ mathrm {answer} $ follows. 1. Prepare an empty stack $ S $. 2. Set $ ​​\ mathrm {answer} = 0 $ 3. Push the root vertex of $ T'$ to $ S $. 4. Extract the first element of $ S $ and make it $ x $. 5. For each child $ c $ of $ x $, do the following with probability $ p $ and do nothing with probability $ 1-p $. * Add vertex $ c $ to $ S $. Then add the weight of the edge connecting $ x $ to $ c $ to $ \ mathrm {answer} $. 6. If S is not empty, transition to 3. 7. Output $ \ mathrm {answer} $. output Print the answer in one line. If the relative or absolute error is less than $ 10 ^ {-6} $, then AC. Also, output a line break at the end. Example Input 0.75 4 1 2 1 2 3 3 3 4 10 Output 24.8569335938 Submitted Solution: ``` p = float(input()) n = int(input()) tree = [] tree_dep = [0] * n t_total = 0 for i in range(n-1): a = list(map(int, input().split())) tree.append(a) tree = sorted(tree) for b in tree: x, y, c = min(b[0], b[1]), max(b[0], b[1]), b[2] dep = tree_dep[x-1] + 1 tree_dep[y-1] = dep t_total += p**dep * c total = t_total for t in tree_dep: total += p**t * t_total print(total) ```
instruction
0
104,386
13
208,772
No
output
1
104,386
13
208,773
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. problem AOR Ika likes rooted trees with a fractal (self-similar) structure. Consider using the weighted rooted tree $ T $ consisting of $ N $ vertices to represent the rooted tree $ T'$ with the following fractal structure. * $ T'$ is the addition of a tree rooted at $ x $ and having a tree structure similar to $ T $ (same cost) for each vertex $ x $ of $ T $. * The root of $ T'$ is the same as that of $ T $. The tree represented in this way is, for example, as shown in the figure below. <image> AOR Ika is trying to do a depth-first search for $ T'$, but finds that it takes a lot of time to trace all the vertices. Therefore, we decided to skip some node visits by performing a depth-first search with a policy of transitioning with a probability of $ p $ and not transitioning with a probability of $ 1-p $ at the time of transition during a depth-first search. Given $ T $ and the probability $ p $, find the expected value of the sum of the costs of all edges to follow when performing a depth-first search for $ T'$. The information of $ T $ is given by the number of vertices $ N $ and the information of the edges of $ N-1 $, and the vertex $ 1 $ is the root. Each vertex is labeled $ 1,2, \ dots, N $, and the $ i \ (1 \ le i \ le N-1) $ th edge costs the vertices $ x_i $ and $ y_i $ $ c_i $ It is tied with. The non-deterministic algorithm of the depth-first search that transitions to a child with a probability of $ p $, which is dealt with in this problem, is expressed as follows. The sum of the costs of the edges that the output $ \ mathrm {answer} $ follows. 1. Prepare an empty stack $ S $. 2. Set $ ​​\ mathrm {answer} = 0 $ 3. Push the root vertex of $ T'$ to $ S $. 4. Extract the first element of $ S $ and make it $ x $. 5. For each child $ c $ of $ x $, do the following with probability $ p $ and do nothing with probability $ 1-p $. * Add vertex $ c $ to $ S $. Then add the weight of the edge connecting $ x $ to $ c $ to $ \ mathrm {answer} $. 6. If S is not empty, transition to 3. 7. Output $ \ mathrm {answer} $. output Print the answer in one line. If the relative or absolute error is less than $ 10 ^ {-6} $, then AC. Also, output a line break at the end. Example Input 0.75 4 1 2 1 2 3 3 3 4 10 Output 24.8569335938 Submitted Solution: ``` p = float(input()) n = int(input()) tree_dep = [0] * n t_total = 0 for i in range(n-1): x, y, c = map(int, input().split()) dep = tree_dep[x-1] + 1 tree_dep[y-1] = dep t_total += p**dep * c total = t_total for t in tree_dep: total += p**t * t_total print(total) ```
instruction
0
104,387
13
208,774
No
output
1
104,387
13
208,775
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. problem AOR Ika likes rooted trees with a fractal (self-similar) structure. Consider using the weighted rooted tree $ T $ consisting of $ N $ vertices to represent the rooted tree $ T'$ with the following fractal structure. * $ T'$ is the addition of a tree rooted at $ x $ and having a tree structure similar to $ T $ (same cost) for each vertex $ x $ of $ T $. * The root of $ T'$ is the same as that of $ T $. The tree represented in this way is, for example, as shown in the figure below. <image> AOR Ika is trying to do a depth-first search for $ T'$, but finds that it takes a lot of time to trace all the vertices. Therefore, we decided to skip some node visits by performing a depth-first search with a policy of transitioning with a probability of $ p $ and not transitioning with a probability of $ 1-p $ at the time of transition during a depth-first search. Given $ T $ and the probability $ p $, find the expected value of the sum of the costs of all edges to follow when performing a depth-first search for $ T'$. The information of $ T $ is given by the number of vertices $ N $ and the information of the edges of $ N-1 $, and the vertex $ 1 $ is the root. Each vertex is labeled $ 1,2, \ dots, N $, and the $ i \ (1 \ le i \ le N-1) $ th edge costs the vertices $ x_i $ and $ y_i $ $ c_i $ It is tied with. The non-deterministic algorithm of the depth-first search that transitions to a child with a probability of $ p $, which is dealt with in this problem, is expressed as follows. The sum of the costs of the edges that the output $ \ mathrm {answer} $ follows. 1. Prepare an empty stack $ S $. 2. Set $ ​​\ mathrm {answer} = 0 $ 3. Push the root vertex of $ T'$ to $ S $. 4. Extract the first element of $ S $ and make it $ x $. 5. For each child $ c $ of $ x $, do the following with probability $ p $ and do nothing with probability $ 1-p $. * Add vertex $ c $ to $ S $. Then add the weight of the edge connecting $ x $ to $ c $ to $ \ mathrm {answer} $. 6. If S is not empty, transition to 3. 7. Output $ \ mathrm {answer} $. output Print the answer in one line. If the relative or absolute error is less than $ 10 ^ {-6} $, then AC. Also, output a line break at the end. Example Input 0.75 4 1 2 1 2 3 3 3 4 10 Output 24.8569335938 Submitted Solution: ``` p = float(input()) N = int(input()) num = {} num[1] = [0, 0] for i in range(N-1): x, y, c = map(int, input().split()) num[y] = [num[x][0]+1, c] t = 0 for i in num.keys(): t += num[i][1] * (p**num[i][0]) d = 0 for i in num.keys(): d += p**num[i][0] print(t+t*d) ```
instruction
0
104,388
13
208,776
No
output
1
104,388
13
208,777
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. problem AOR Ika likes rooted trees with a fractal (self-similar) structure. Consider using the weighted rooted tree $ T $ consisting of $ N $ vertices to represent the rooted tree $ T'$ with the following fractal structure. * $ T'$ is the addition of a tree rooted at $ x $ and having a tree structure similar to $ T $ (same cost) for each vertex $ x $ of $ T $. * The root of $ T'$ is the same as that of $ T $. The tree represented in this way is, for example, as shown in the figure below. <image> AOR Ika is trying to do a depth-first search for $ T'$, but finds that it takes a lot of time to trace all the vertices. Therefore, we decided to skip some node visits by performing a depth-first search with a policy of transitioning with a probability of $ p $ and not transitioning with a probability of $ 1-p $ at the time of transition during a depth-first search. Given $ T $ and the probability $ p $, find the expected value of the sum of the costs of all edges to follow when performing a depth-first search for $ T'$. The information of $ T $ is given by the number of vertices $ N $ and the information of the edges of $ N-1 $, and the vertex $ 1 $ is the root. Each vertex is labeled $ 1,2, \ dots, N $, and the $ i \ (1 \ le i \ le N-1) $ th edge costs the vertices $ x_i $ and $ y_i $ $ c_i $ It is tied with. The non-deterministic algorithm of the depth-first search that transitions to a child with a probability of $ p $, which is dealt with in this problem, is expressed as follows. The sum of the costs of the edges that the output $ \ mathrm {answer} $ follows. 1. Prepare an empty stack $ S $. 2. Set $ ​​\ mathrm {answer} = 0 $ 3. Push the root vertex of $ T'$ to $ S $. 4. Extract the first element of $ S $ and make it $ x $. 5. For each child $ c $ of $ x $, do the following with probability $ p $ and do nothing with probability $ 1-p $. * Add vertex $ c $ to $ S $. Then add the weight of the edge connecting $ x $ to $ c $ to $ \ mathrm {answer} $. 6. If S is not empty, transition to 3. 7. Output $ \ mathrm {answer} $. output Print the answer in one line. If the relative or absolute error is less than $ 10 ^ {-6} $, then AC. Also, output a line break at the end. Example Input 0.75 4 1 2 1 2 3 3 3 4 10 Output 24.8569335938 Submitted Solution: ``` p = float(input()) n = int(input()) tree = [] tree_dep = [0] * n t_total = 0 for i in range(n-1): a = list(map(int, input().split())) tree.append(a) tree = sorted(tree) for b in tree: #x, y, c = map(int, input().split()) x, y, c = b[0], b[1], b[2] dep = tree_dep[x-1] + 1 tree_dep[y-1] = dep t_total += p**dep * c total = t_total for t in tree_dep: total += p**t * t_total print(total) ```
instruction
0
104,389
13
208,778
No
output
1
104,389
13
208,779
Provide tags and a correct Python 3 solution for this coding contest problem. You are given three integers n, d and k. Your task is to construct an undirected tree on n vertices with diameter d and degree of each vertex at most k, or say that it is impossible. An undirected tree is a connected undirected graph with n - 1 edges. Diameter of a tree is the maximum length of a simple path (a path in which each vertex appears at most once) between all pairs of vertices of this tree. Degree of a vertex is the number of edges incident to this vertex (i.e. for a vertex u it is the number of edges (u, v) that belong to the tree, where v is any other vertex of a tree). Input The first line of the input contains three integers n, d and k (1 ≤ n, d, k ≤ 4 ⋅ 10^5). Output If there is no tree satisfying the conditions above, print only one word "NO" (without quotes). Otherwise in the first line print "YES" (without quotes), and then print n - 1 lines describing edges of a tree satisfying the conditions above. Vertices of the tree must be numbered from 1 to n. You can print edges and vertices connected by an edge in any order. If there are multiple answers, print any of them.1 Examples Input 6 3 3 Output YES 3 1 4 1 1 2 5 2 2 6 Input 6 2 3 Output NO Input 10 4 3 Output YES 2 9 2 10 10 3 3 1 6 10 8 2 4 3 5 6 6 7 Input 8 5 3 Output YES 2 5 7 2 3 7 3 1 1 6 8 7 4 3
instruction
0
104,422
13
208,844
Tags: constructive algorithms, graphs Correct Solution: ``` from sys import exit def bad(): print("NO") exit() node = 1 def make_branch(u, d, deg, g, n, k): global node while deg[u] < k and d > 0 and node < n: node += 1 deg[u] += 1 deg[node] = 1 g[u].append(node) make_branch(node, d - 1, deg, g, n, k) def main(): global node n, d, k = map(int, input().split()) if d >= n or (k == 1 and n > 2): bad() g = [[] for _ in range(n + 5)] deg = [0 for _ in range(n + 5)] for i in range(1, d + 1): g[i].append(i + 1) deg[i] += 1 deg[i + 1] += 1 node = d + 1 LD = 1 RD = d - 1 for u in range(2, d + 1): make_branch(u, min(LD, RD), deg, g, n, k) LD += 1 RD -= 1 used = [False for _ in range(n + 5)] q = [[1, 1]] used[1] = True while len(q) > 0: u, p = q.pop() for v in g[u]: if v != p: used[v] = True q.append([v, u]) for i in range(1, n + 1): if used[i] == False: bad() print("YES") for u in range(1, n + 1): for v in g[u]: print(u, v) main() ```
output
1
104,422
13
208,845
Provide tags and a correct Python 3 solution for this coding contest problem. You are given three integers n, d and k. Your task is to construct an undirected tree on n vertices with diameter d and degree of each vertex at most k, or say that it is impossible. An undirected tree is a connected undirected graph with n - 1 edges. Diameter of a tree is the maximum length of a simple path (a path in which each vertex appears at most once) between all pairs of vertices of this tree. Degree of a vertex is the number of edges incident to this vertex (i.e. for a vertex u it is the number of edges (u, v) that belong to the tree, where v is any other vertex of a tree). Input The first line of the input contains three integers n, d and k (1 ≤ n, d, k ≤ 4 ⋅ 10^5). Output If there is no tree satisfying the conditions above, print only one word "NO" (without quotes). Otherwise in the first line print "YES" (without quotes), and then print n - 1 lines describing edges of a tree satisfying the conditions above. Vertices of the tree must be numbered from 1 to n. You can print edges and vertices connected by an edge in any order. If there are multiple answers, print any of them.1 Examples Input 6 3 3 Output YES 3 1 4 1 1 2 5 2 2 6 Input 6 2 3 Output NO Input 10 4 3 Output YES 2 9 2 10 10 3 3 1 6 10 8 2 4 3 5 6 6 7 Input 8 5 3 Output YES 2 5 7 2 3 7 3 1 1 6 8 7 4 3
instruction
0
104,423
13
208,846
Tags: constructive algorithms, graphs Correct Solution: ``` n, d, k = map(int, input().split()) if d+1 > n: print('NO') exit() ans = [] dist = [0]*n deg = [0]*n for i in range(d+1): if i == 0 or i == d: deg[i] = 1 else: deg[i] = 2 if i != d: ans.append((i+1, i+2)) dist[i] = max(i, d-i) for i in range(n): if deg[i] > k: print('NO') exit() from collections import deque q = deque(list(range(d+1))) cur = d+1 while q and cur < n: v = q.popleft() if dist[v] < d and deg[v] < k: deg[v] += 1 dist[cur] = dist[v]+1 deg[cur] = 1 ans.append((v+1, cur+1)) q.append(v) q.append(cur) cur += 1 else: continue if cur != n: print('NO') else: print('YES') for i in range(len(ans)): print(*ans[i]) ```
output
1
104,423
13
208,847
Provide tags and a correct Python 3 solution for this coding contest problem. You are given three integers n, d and k. Your task is to construct an undirected tree on n vertices with diameter d and degree of each vertex at most k, or say that it is impossible. An undirected tree is a connected undirected graph with n - 1 edges. Diameter of a tree is the maximum length of a simple path (a path in which each vertex appears at most once) between all pairs of vertices of this tree. Degree of a vertex is the number of edges incident to this vertex (i.e. for a vertex u it is the number of edges (u, v) that belong to the tree, where v is any other vertex of a tree). Input The first line of the input contains three integers n, d and k (1 ≤ n, d, k ≤ 4 ⋅ 10^5). Output If there is no tree satisfying the conditions above, print only one word "NO" (without quotes). Otherwise in the first line print "YES" (without quotes), and then print n - 1 lines describing edges of a tree satisfying the conditions above. Vertices of the tree must be numbered from 1 to n. You can print edges and vertices connected by an edge in any order. If there are multiple answers, print any of them.1 Examples Input 6 3 3 Output YES 3 1 4 1 1 2 5 2 2 6 Input 6 2 3 Output NO Input 10 4 3 Output YES 2 9 2 10 10 3 3 1 6 10 8 2 4 3 5 6 6 7 Input 8 5 3 Output YES 2 5 7 2 3 7 3 1 1 6 8 7 4 3
instruction
0
104,424
13
208,848
Tags: constructive algorithms, graphs Correct Solution: ``` import sys input = sys.stdin.buffer.readline from collections import deque n,d,k=map(int,input().split()) if d>=n: print("NO") exit() graph=[[] for i in range(n+1)] for i in range(1,d+2): graph[i].append(min(i-1,d+1-i)) # print(graph) for i in range(1,d+1): graph[i].append(i+1) graph[i+1].append(i) # print(graph) deg=[0]*(n+1) deg[1]=1 deg[d+1]=1 for i in range(2,d+1): deg[i]=2 # print(deg) for i in deg: if i>k: print("NO") exit() p=d+2 for i in range(1,d+2): q=deque() q.append(i) while len(q)!=0: x=q.popleft() while (graph[x][0]>0 and deg[x]<k and p<=n): graph[x].append(p) deg[x]=deg[x]+1 graph[p].append(graph[x][0]-1) graph[p].append(x) deg[p]=deg[p]+1 q.append(p) p=p+1 # print(graph) if p<=n: print("NO") else: print("YES") vis=[-1]*(n+1) for i in range(1,d+2): if vis[i]==-1: q=deque() q.append(i) while len(q)!=0: x=q.popleft() vis[x]=1 for j in range(1,len(graph[x])): if vis[graph[x][j]]==-1: print(x,graph[x][j]) q.append(graph[x][j]) ```
output
1
104,424
13
208,849
Provide tags and a correct Python 3 solution for this coding contest problem. You are given three integers n, d and k. Your task is to construct an undirected tree on n vertices with diameter d and degree of each vertex at most k, or say that it is impossible. An undirected tree is a connected undirected graph with n - 1 edges. Diameter of a tree is the maximum length of a simple path (a path in which each vertex appears at most once) between all pairs of vertices of this tree. Degree of a vertex is the number of edges incident to this vertex (i.e. for a vertex u it is the number of edges (u, v) that belong to the tree, where v is any other vertex of a tree). Input The first line of the input contains three integers n, d and k (1 ≤ n, d, k ≤ 4 ⋅ 10^5). Output If there is no tree satisfying the conditions above, print only one word "NO" (without quotes). Otherwise in the first line print "YES" (without quotes), and then print n - 1 lines describing edges of a tree satisfying the conditions above. Vertices of the tree must be numbered from 1 to n. You can print edges and vertices connected by an edge in any order. If there are multiple answers, print any of them.1 Examples Input 6 3 3 Output YES 3 1 4 1 1 2 5 2 2 6 Input 6 2 3 Output NO Input 10 4 3 Output YES 2 9 2 10 10 3 3 1 6 10 8 2 4 3 5 6 6 7 Input 8 5 3 Output YES 2 5 7 2 3 7 3 1 1 6 8 7 4 3
instruction
0
104,425
13
208,850
Tags: constructive algorithms, graphs Correct Solution: ``` #WARNING This code is just for fun. Reading it might give u a brainfreeze n,d,k = [int(x) for x in input().strip().split(' ')] l = [] i = 1 if n<=d: print("NO") elif k==1: if n>2: print("NO") elif n==2: print("YES") print(1,2) else: n+=1 flag = False while i<min(d+1,n): l.append(str(i)+" "+str(i+1)) i+=1 i+=1 cnt1=0 cnt2=1 se=[[2,d+1,1]] while cnt1<cnt2: start = se[cnt1][0] end = se[cnt1][1] mode = se[cnt1][2] #print(se) kk = 3 while (i<n) and (kk<=k): if i<n and not flag: j = start #print(j,"kk") while i<n and j<end: if mode==1: c = min(j-start+1,end-j) else: c = min(end-j,d-end+j) if c>1: se.append([i,i+c-1,2]) cnt2+=1 ki=j while i<n and c>0: l.append(str(ki)+" "+str(i)) #print(j,i,c) c-=1 ki=i i+=1 j+=1 else: flag = True break kk+=1 cnt1+=1 if i<n or flag: #print(l) print("NO") else: print("YES") print('\n'.join(l)) ```
output
1
104,425
13
208,851
Provide tags and a correct Python 3 solution for this coding contest problem. You are given three integers n, d and k. Your task is to construct an undirected tree on n vertices with diameter d and degree of each vertex at most k, or say that it is impossible. An undirected tree is a connected undirected graph with n - 1 edges. Diameter of a tree is the maximum length of a simple path (a path in which each vertex appears at most once) between all pairs of vertices of this tree. Degree of a vertex is the number of edges incident to this vertex (i.e. for a vertex u it is the number of edges (u, v) that belong to the tree, where v is any other vertex of a tree). Input The first line of the input contains three integers n, d and k (1 ≤ n, d, k ≤ 4 ⋅ 10^5). Output If there is no tree satisfying the conditions above, print only one word "NO" (without quotes). Otherwise in the first line print "YES" (without quotes), and then print n - 1 lines describing edges of a tree satisfying the conditions above. Vertices of the tree must be numbered from 1 to n. You can print edges and vertices connected by an edge in any order. If there are multiple answers, print any of them.1 Examples Input 6 3 3 Output YES 3 1 4 1 1 2 5 2 2 6 Input 6 2 3 Output NO Input 10 4 3 Output YES 2 9 2 10 10 3 3 1 6 10 8 2 4 3 5 6 6 7 Input 8 5 3 Output YES 2 5 7 2 3 7 3 1 1 6 8 7 4 3
instruction
0
104,426
13
208,852
Tags: constructive algorithms, graphs Correct Solution: ``` import sys n,d,k=map(int,input().split()) if(n<=d): print('NO') sys.exit() if(k==1 and n>2): print('NO') sys.exit() edgestot=[] edges=[[] for i in range(n)] tovisit=[] for i in range(d): edgestot.append([i,i+1]) tovisit.append([i+1,min(i+1,d-i-1)]) edges[i].append(i+1) edges[i+1].append(i) cur=d+1 while(cur<n and len(tovisit)>0): x=tovisit.pop() if(x[1]==0): continue while(len(edges[x[0]])<k and cur<n): tovisit.append([cur,x[1]-1]) edgestot.append([cur,x[0]]) edges[x[0]].append(cur) edges[cur].append(x[0]) cur+=1 #print(edgestot) if(len(edgestot)==n-1): print('YES') for i in range(n-1): print(edgestot[i][0]+1,edgestot[i][1]+1) else: print('NO') ```
output
1
104,426
13
208,853
Provide tags and a correct Python 3 solution for this coding contest problem. You are given three integers n, d and k. Your task is to construct an undirected tree on n vertices with diameter d and degree of each vertex at most k, or say that it is impossible. An undirected tree is a connected undirected graph with n - 1 edges. Diameter of a tree is the maximum length of a simple path (a path in which each vertex appears at most once) between all pairs of vertices of this tree. Degree of a vertex is the number of edges incident to this vertex (i.e. for a vertex u it is the number of edges (u, v) that belong to the tree, where v is any other vertex of a tree). Input The first line of the input contains three integers n, d and k (1 ≤ n, d, k ≤ 4 ⋅ 10^5). Output If there is no tree satisfying the conditions above, print only one word "NO" (without quotes). Otherwise in the first line print "YES" (without quotes), and then print n - 1 lines describing edges of a tree satisfying the conditions above. Vertices of the tree must be numbered from 1 to n. You can print edges and vertices connected by an edge in any order. If there are multiple answers, print any of them.1 Examples Input 6 3 3 Output YES 3 1 4 1 1 2 5 2 2 6 Input 6 2 3 Output NO Input 10 4 3 Output YES 2 9 2 10 10 3 3 1 6 10 8 2 4 3 5 6 6 7 Input 8 5 3 Output YES 2 5 7 2 3 7 3 1 1 6 8 7 4 3
instruction
0
104,427
13
208,854
Tags: constructive algorithms, graphs Correct Solution: ``` def main(): n, d, k = list(map(int, input().split())) if n == 2 and d == 1 and k == 1: print("YES") print("1 2") return 0 if n == d + 1 and k - 1: print("YES") for i in range(1, d + 1): print(i, i + 1) return 0 if n < d +1 or k <= 2 or d == 1: print("NO") return 0 if d % 2 == 0: if n * (k - 2) > -2 + k * (k - 1) ** (d // 2): print("NO") return 0 print("YES") for i in range(1, d + 1): print(i, i + 1) nodes = d + 1 leaves = [1 + d // 2] dev = 0 while True: new_leaves = [] for i in leaves: for j in range(k - 1 - (i <= d + 1)): nodes += 1 print(i, nodes) new_leaves.append(nodes) if nodes == n: return 0 dev += 1 leaves = new_leaves + [1 - dev + d // 2, 1 + dev + d // 2] else: if n * (k - 2) > -2 + k * (k - 1) ** (d // 2) + (k - 2) * (k - 1) ** (d // 2): print("NO") return 0 print("YES") for i in range(1, d + 1): print(i, i + 1) nodes = d + 1 leaves = [1 + d // 2, 2 + d // 2] dev = 0 while True: new_leaves = [] for i in leaves: for j in range(k - 1 - (i <= d + 1)): nodes += 1 print(i, nodes) new_leaves.append(nodes) if nodes == n: return 0 dev += 1 leaves = new_leaves + [1 - dev + d // 2, 2 + dev + d // 2] main() ```
output
1
104,427
13
208,855
Provide tags and a correct Python 3 solution for this coding contest problem. You are given three integers n, d and k. Your task is to construct an undirected tree on n vertices with diameter d and degree of each vertex at most k, or say that it is impossible. An undirected tree is a connected undirected graph with n - 1 edges. Diameter of a tree is the maximum length of a simple path (a path in which each vertex appears at most once) between all pairs of vertices of this tree. Degree of a vertex is the number of edges incident to this vertex (i.e. for a vertex u it is the number of edges (u, v) that belong to the tree, where v is any other vertex of a tree). Input The first line of the input contains three integers n, d and k (1 ≤ n, d, k ≤ 4 ⋅ 10^5). Output If there is no tree satisfying the conditions above, print only one word "NO" (without quotes). Otherwise in the first line print "YES" (without quotes), and then print n - 1 lines describing edges of a tree satisfying the conditions above. Vertices of the tree must be numbered from 1 to n. You can print edges and vertices connected by an edge in any order. If there are multiple answers, print any of them.1 Examples Input 6 3 3 Output YES 3 1 4 1 1 2 5 2 2 6 Input 6 2 3 Output NO Input 10 4 3 Output YES 2 9 2 10 10 3 3 1 6 10 8 2 4 3 5 6 6 7 Input 8 5 3 Output YES 2 5 7 2 3 7 3 1 1 6 8 7 4 3
instruction
0
104,428
13
208,856
Tags: constructive algorithms, graphs Correct Solution: ``` n, d, k = map(int, input().split()) num = d+2 def solve(): global num if n == 1: return 'NO' if n == 2: if d != 1: return 'NO' else: return "YES\n1 2" if k < 2: return 'NO' if d > n-1: return 'NO' depth = [min(i, d-i) for i in range(d+1)] ans = [(i+1, i+2) for i in range(d)] def dfs(v, depth): global num if depth == 0: return for i in range(k-1): if len(ans) == n-1: return v2 = num num += 1 ans.append((v, v2)) dfs(v2, depth-1) for v in range(d+1): if depth[v] == 0: continue for i in range(k-2): if len(ans) == n-1: break v2 = num num += 1 ans.append((v+1, v2)) if depth[v] > 1: dfs(v2, depth[v]-1) if len(ans) < n-1: return "NO" return "YES\n%s"%"\n".join(["%d %d"%i for i in ans]) print(solve()) ```
output
1
104,428
13
208,857
Provide tags and a correct Python 3 solution for this coding contest problem. You are given three integers n, d and k. Your task is to construct an undirected tree on n vertices with diameter d and degree of each vertex at most k, or say that it is impossible. An undirected tree is a connected undirected graph with n - 1 edges. Diameter of a tree is the maximum length of a simple path (a path in which each vertex appears at most once) between all pairs of vertices of this tree. Degree of a vertex is the number of edges incident to this vertex (i.e. for a vertex u it is the number of edges (u, v) that belong to the tree, where v is any other vertex of a tree). Input The first line of the input contains three integers n, d and k (1 ≤ n, d, k ≤ 4 ⋅ 10^5). Output If there is no tree satisfying the conditions above, print only one word "NO" (without quotes). Otherwise in the first line print "YES" (without quotes), and then print n - 1 lines describing edges of a tree satisfying the conditions above. Vertices of the tree must be numbered from 1 to n. You can print edges and vertices connected by an edge in any order. If there are multiple answers, print any of them.1 Examples Input 6 3 3 Output YES 3 1 4 1 1 2 5 2 2 6 Input 6 2 3 Output NO Input 10 4 3 Output YES 2 9 2 10 10 3 3 1 6 10 8 2 4 3 5 6 6 7 Input 8 5 3 Output YES 2 5 7 2 3 7 3 1 1 6 8 7 4 3
instruction
0
104,429
13
208,858
Tags: constructive algorithms, graphs Correct Solution: ``` n,d,k=map(int,input().strip().split()) ans=[] if (d>n-1): print ("NO") exit(0) if (k<2 and n>2): print ("NO") exit(0) l1=[0 for i in range(d+2)] count=d cnt=d+2 def insert(par,v,r,e): global count global cnt if count==n-1: print ("YES") for o in ans: print (o[0],o[1]) exit(0) else: ans.append([par,v]) cnt=cnt+1 count=count+1 if (e==0): return while(r!=0): insert(v,cnt,k-1,e-1) r=r-1 return for i in range(1,d+1): ans.append([i,i+1]) for i in range(1,d+2): l1[i]=min(i-1,d+1-i) for i in range(2,d+1): r=k-2 while(r!=0): insert(i,cnt,k-1,l1[i]-1) r=r-1 if (count<n-1): print ("NO") else: print ("YES") for o in ans: print (o[0],o[1]) exit(0) ```
output
1
104,429
13
208,859
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given three integers n, d and k. Your task is to construct an undirected tree on n vertices with diameter d and degree of each vertex at most k, or say that it is impossible. An undirected tree is a connected undirected graph with n - 1 edges. Diameter of a tree is the maximum length of a simple path (a path in which each vertex appears at most once) between all pairs of vertices of this tree. Degree of a vertex is the number of edges incident to this vertex (i.e. for a vertex u it is the number of edges (u, v) that belong to the tree, where v is any other vertex of a tree). Input The first line of the input contains three integers n, d and k (1 ≤ n, d, k ≤ 4 ⋅ 10^5). Output If there is no tree satisfying the conditions above, print only one word "NO" (without quotes). Otherwise in the first line print "YES" (without quotes), and then print n - 1 lines describing edges of a tree satisfying the conditions above. Vertices of the tree must be numbered from 1 to n. You can print edges and vertices connected by an edge in any order. If there are multiple answers, print any of them.1 Examples Input 6 3 3 Output YES 3 1 4 1 1 2 5 2 2 6 Input 6 2 3 Output NO Input 10 4 3 Output YES 2 9 2 10 10 3 3 1 6 10 8 2 4 3 5 6 6 7 Input 8 5 3 Output YES 2 5 7 2 3 7 3 1 1 6 8 7 4 3 Submitted Solution: ``` """Sorted List ============== :doc:`Sorted Containers<index>` is an Apache2 licensed Python sorted collections library, written in pure-Python, and fast as C-extensions. The :doc:`introduction<introduction>` is the best way to get started. Sorted list implementations: .. currentmodule:: sortedcontainers * :class:`SortedList` * :class:`SortedKeyList` """ # pylint: disable=too-many-lines from __future__ import print_function from bisect import bisect_left, bisect_right, insort from collections import Sequence, MutableSequence from itertools import chain, repeat, starmap from math import log from operator import add, eq, ne, gt, ge, lt, le, iadd from textwrap import dedent ############################################################################### # BEGIN Python 2/3 Shims ############################################################################### from functools import wraps from sys import hexversion if hexversion < 0x03000000: from itertools import imap as map # pylint: disable=redefined-builtin from itertools import izip as zip # pylint: disable=redefined-builtin try: from thread import get_ident except ImportError: from dummy_thread import get_ident else: from functools import reduce try: from _thread import get_ident except ImportError: from _dummy_thread import get_ident def recursive_repr(fillvalue='...'): "Decorator to make a repr function return fillvalue for a recursive call." # pylint: disable=missing-docstring # Copied from reprlib in Python 3 # https://hg.python.org/cpython/file/3.6/Lib/reprlib.py def decorating_function(user_function): repr_running = set() @wraps(user_function) def wrapper(self): key = id(self), get_ident() if key in repr_running: return fillvalue repr_running.add(key) try: result = user_function(self) finally: repr_running.discard(key) return result return wrapper return decorating_function ############################################################################### # END Python 2/3 Shims ############################################################################### class SortedList(MutableSequence): """Sorted list is a sorted mutable sequence. Sorted list values are maintained in sorted order. Sorted list values must be comparable. The total ordering of values must not change while they are stored in the sorted list. Methods for adding values: * :func:`SortedList.add` * :func:`SortedList.update` * :func:`SortedList.__add__` * :func:`SortedList.__iadd__` * :func:`SortedList.__mul__` * :func:`SortedList.__imul__` Methods for removing values: * :func:`SortedList.clear` * :func:`SortedList.discard` * :func:`SortedList.remove` * :func:`SortedList.pop` * :func:`SortedList.__delitem__` Methods for looking up values: * :func:`SortedList.bisect_left` * :func:`SortedList.bisect_right` * :func:`SortedList.count` * :func:`SortedList.index` * :func:`SortedList.__contains__` * :func:`SortedList.__getitem__` Methods for iterating values: * :func:`SortedList.irange` * :func:`SortedList.islice` * :func:`SortedList.__iter__` * :func:`SortedList.__reversed__` Methods for miscellany: * :func:`SortedList.copy` * :func:`SortedList.__len__` * :func:`SortedList.__repr__` * :func:`SortedList._check` * :func:`SortedList._reset` Sorted lists use lexicographical ordering semantics when compared to other sequences. Some methods of mutable sequences are not supported and will raise not-implemented error. """ DEFAULT_LOAD_FACTOR = 1000 def __init__(self, iterable=None, key=None): """Initialize sorted list instance. Optional `iterable` argument provides an initial iterable of values to initialize the sorted list. Runtime complexity: `O(n*log(n))` >>> sl = SortedList() >>> sl SortedList([]) >>> sl = SortedList([3, 1, 2, 5, 4]) >>> sl SortedList([1, 2, 3, 4, 5]) :param iterable: initial values (optional) """ assert key is None self._len = 0 self._load = self.DEFAULT_LOAD_FACTOR self._lists = [] self._maxes = [] self._index = [] self._offset = 0 if iterable is not None: self._update(iterable) def __new__(cls, iterable=None, key=None): """Create new sorted list or sorted-key list instance. Optional `key`-function argument will return an instance of subtype :class:`SortedKeyList`. >>> sl = SortedList() >>> isinstance(sl, SortedList) True >>> sl = SortedList(key=lambda x: -x) >>> isinstance(sl, SortedList) True >>> isinstance(sl, SortedKeyList) True :param iterable: initial values (optional) :param key: function used to extract comparison key (optional) :return: sorted list or sorted-key list instance """ # pylint: disable=unused-argument if key is None: return object.__new__(cls) else: if cls is SortedList: return object.__new__(SortedKeyList) else: raise TypeError('inherit SortedKeyList for key argument') @property def key(self): """Function used to extract comparison key from values. Sorted list compares values directly so the key function is none. """ return None def _reset(self, load): """Reset sorted list load factor. The `load` specifies the load-factor of the list. The default load factor of 1000 works well for lists from tens to tens-of-millions of values. Good practice is to use a value that is the cube root of the list size. With billions of elements, the best load factor depends on your usage. It's best to leave the load factor at the default until you start benchmarking. See :doc:`implementation` and :doc:`performance-scale` for more information. Runtime complexity: `O(n)` :param int load: load-factor for sorted list sublists """ values = reduce(iadd, self._lists, []) self._clear() self._load = load self._update(values) def clear(self): """Remove all values from sorted list. Runtime complexity: `O(n)` """ self._len = 0 del self._lists[:] del self._maxes[:] del self._index[:] self._offset = 0 _clear = clear def add(self, value): """Add `value` to sorted list. Runtime complexity: `O(log(n))` -- approximate. >>> sl = SortedList() >>> sl.add(3) >>> sl.add(1) >>> sl.add(2) >>> sl SortedList([1, 2, 3]) :param value: value to add to sorted list """ _lists = self._lists _maxes = self._maxes if _maxes: pos = bisect_right(_maxes, value) if pos == len(_maxes): pos -= 1 _lists[pos].append(value) _maxes[pos] = value else: insort(_lists[pos], value) self._expand(pos) else: _lists.append([value]) _maxes.append(value) self._len += 1 def _expand(self, pos): """Split sublists with length greater than double the load-factor. Updates the index when the sublist length is less than double the load level. This requires incrementing the nodes in a traversal from the leaf node to the root. For an example traversal see ``SortedList._loc``. """ _load = self._load _lists = self._lists _index = self._index if len(_lists[pos]) > (_load << 1): _maxes = self._maxes _lists_pos = _lists[pos] half = _lists_pos[_load:] del _lists_pos[_load:] _maxes[pos] = _lists_pos[-1] _lists.insert(pos + 1, half) _maxes.insert(pos + 1, half[-1]) del _index[:] else: if _index: child = self._offset + pos while child: _index[child] += 1 child = (child - 1) >> 1 _index[0] += 1 def update(self, iterable): """Update sorted list by adding all values from `iterable`. Runtime complexity: `O(k*log(n))` -- approximate. >>> sl = SortedList() >>> sl.update([3, 1, 2]) >>> sl SortedList([1, 2, 3]) :param iterable: iterable of values to add """ _lists = self._lists _maxes = self._maxes values = sorted(iterable) if _maxes: if len(values) * 4 >= self._len: values.extend(chain.from_iterable(_lists)) values.sort() self._clear() else: _add = self.add for val in values: _add(val) return _load = self._load _lists.extend(values[pos:(pos + _load)] for pos in range(0, len(values), _load)) _maxes.extend(sublist[-1] for sublist in _lists) self._len = len(values) del self._index[:] _update = update def __contains__(self, value): """Return true if `value` is an element of the sorted list. ``sl.__contains__(value)`` <==> ``value in sl`` Runtime complexity: `O(log(n))` >>> sl = SortedList([1, 2, 3, 4, 5]) >>> 3 in sl True :param value: search for value in sorted list :return: true if `value` in sorted list """ _maxes = self._maxes if not _maxes: return False pos = bisect_left(_maxes, value) if pos == len(_maxes): return False _lists = self._lists idx = bisect_left(_lists[pos], value) return _lists[pos][idx] == value def discard(self, value): """Remove `value` from sorted list if it is a member. If `value` is not a member, do nothing. Runtime complexity: `O(log(n))` -- approximate. >>> sl = SortedList([1, 2, 3, 4, 5]) >>> sl.discard(5) >>> sl.discard(0) >>> sl == [1, 2, 3, 4] True :param value: `value` to discard from sorted list """ _maxes = self._maxes if not _maxes: return pos = bisect_left(_maxes, value) if pos == len(_maxes): return _lists = self._lists idx = bisect_left(_lists[pos], value) if _lists[pos][idx] == value: self._delete(pos, idx) def remove(self, value): """Remove `value` from sorted list; `value` must be a member. If `value` is not a member, raise ValueError. Runtime complexity: `O(log(n))` -- approximate. >>> sl = SortedList([1, 2, 3, 4, 5]) >>> sl.remove(5) >>> sl == [1, 2, 3, 4] True >>> sl.remove(0) Traceback (most recent call last): ... ValueError: 0 not in list :param value: `value` to remove from sorted list :raises ValueError: if `value` is not in sorted list """ _maxes = self._maxes if not _maxes: raise ValueError('{0!r} not in list'.format(value)) pos = bisect_left(_maxes, value) if pos == len(_maxes): raise ValueError('{0!r} not in list'.format(value)) _lists = self._lists idx = bisect_left(_lists[pos], value) if _lists[pos][idx] == value: self._delete(pos, idx) else: raise ValueError('{0!r} not in list'.format(value)) def _delete(self, pos, idx): """Delete value at the given `(pos, idx)`. Combines lists that are less than half the load level. Updates the index when the sublist length is more than half the load level. This requires decrementing the nodes in a traversal from the leaf node to the root. For an example traversal see ``SortedList._loc``. :param int pos: lists index :param int idx: sublist index """ _lists = self._lists _maxes = self._maxes _index = self._index _lists_pos = _lists[pos] del _lists_pos[idx] self._len -= 1 len_lists_pos = len(_lists_pos) if len_lists_pos > (self._load >> 1): _maxes[pos] = _lists_pos[-1] if _index: child = self._offset + pos while child > 0: _index[child] -= 1 child = (child - 1) >> 1 _index[0] -= 1 elif len(_lists) > 1: if not pos: pos += 1 prev = pos - 1 _lists[prev].extend(_lists[pos]) _maxes[prev] = _lists[prev][-1] del _lists[pos] del _maxes[pos] del _index[:] self._expand(prev) elif len_lists_pos: _maxes[pos] = _lists_pos[-1] else: del _lists[pos] del _maxes[pos] del _index[:] def _loc(self, pos, idx): """Convert an index pair (lists index, sublist index) into a single index number that corresponds to the position of the value in the sorted list. Many queries require the index be built. Details of the index are described in ``SortedList._build_index``. Indexing requires traversing the tree from a leaf node to the root. The parent of each node is easily computable at ``(pos - 1) // 2``. Left-child nodes are always at odd indices and right-child nodes are always at even indices. When traversing up from a right-child node, increment the total by the left-child node. The final index is the sum from traversal and the index in the sublist. For example, using the index from ``SortedList._build_index``:: _index = 14 5 9 3 2 4 5 _offset = 3 Tree:: 14 5 9 3 2 4 5 Converting an index pair (2, 3) into a single index involves iterating like so: 1. Starting at the leaf node: offset + alpha = 3 + 2 = 5. We identify the node as a left-child node. At such nodes, we simply traverse to the parent. 2. At node 9, position 2, we recognize the node as a right-child node and accumulate the left-child in our total. Total is now 5 and we traverse to the parent at position 0. 3. Iteration ends at the root. The index is then the sum of the total and sublist index: 5 + 3 = 8. :param int pos: lists index :param int idx: sublist index :return: index in sorted list """ if not pos: return idx _index = self._index if not _index: self._build_index() total = 0 # Increment pos to point in the index to len(self._lists[pos]). pos += self._offset # Iterate until reaching the root of the index tree at pos = 0. while pos: # Right-child nodes are at odd indices. At such indices # account the total below the left child node. if not pos & 1: total += _index[pos - 1] # Advance pos to the parent node. pos = (pos - 1) >> 1 return total + idx def _pos(self, idx): """Convert an index into an index pair (lists index, sublist index) that can be used to access the corresponding lists position. Many queries require the index be built. Details of the index are described in ``SortedList._build_index``. Indexing requires traversing the tree to a leaf node. Each node has two children which are easily computable. Given an index, pos, the left-child is at ``pos * 2 + 1`` and the right-child is at ``pos * 2 + 2``. When the index is less than the left-child, traversal moves to the left sub-tree. Otherwise, the index is decremented by the left-child and traversal moves to the right sub-tree. At a child node, the indexing pair is computed from the relative position of the child node as compared with the offset and the remaining index. For example, using the index from ``SortedList._build_index``:: _index = 14 5 9 3 2 4 5 _offset = 3 Tree:: 14 5 9 3 2 4 5 Indexing position 8 involves iterating like so: 1. Starting at the root, position 0, 8 is compared with the left-child node (5) which it is greater than. When greater the index is decremented and the position is updated to the right child node. 2. At node 9 with index 3, we again compare the index to the left-child node with value 4. Because the index is the less than the left-child node, we simply traverse to the left. 3. At node 4 with index 3, we recognize that we are at a leaf node and stop iterating. 4. To compute the sublist index, we subtract the offset from the index of the leaf node: 5 - 3 = 2. To compute the index in the sublist, we simply use the index remaining from iteration. In this case, 3. The final index pair from our example is (2, 3) which corresponds to index 8 in the sorted list. :param int idx: index in sorted list :return: (lists index, sublist index) pair """ if idx < 0: last_len = len(self._lists[-1]) if (-idx) <= last_len: return len(self._lists) - 1, last_len + idx idx += self._len if idx < 0: raise IndexError('list index out of range') elif idx >= self._len: raise IndexError('list index out of range') if idx < len(self._lists[0]): return 0, idx _index = self._index if not _index: self._build_index() pos = 0 child = 1 len_index = len(_index) while child < len_index: index_child = _index[child] if idx < index_child: pos = child else: idx -= index_child pos = child + 1 child = (pos << 1) + 1 return (pos - self._offset, idx) def _build_index(self): """Build a positional index for indexing the sorted list. Indexes are represented as binary trees in a dense array notation similar to a binary heap. For example, given a lists representation storing integers:: 0: [1, 2, 3] 1: [4, 5] 2: [6, 7, 8, 9] 3: [10, 11, 12, 13, 14] The first transformation maps the sub-lists by their length. The first row of the index is the length of the sub-lists:: 0: [3, 2, 4, 5] Each row after that is the sum of consecutive pairs of the previous row:: 1: [5, 9] 2: [14] Finally, the index is built by concatenating these lists together:: _index = [14, 5, 9, 3, 2, 4, 5] An offset storing the start of the first row is also stored:: _offset = 3 When built, the index can be used for efficient indexing into the list. See the comment and notes on ``SortedList._pos`` for details. """ row0 = list(map(len, self._lists)) if len(row0) == 1: self._index[:] = row0 self._offset = 0 return head = iter(row0) tail = iter(head) row1 = list(starmap(add, zip(head, tail))) if len(row0) & 1: row1.append(row0[-1]) if len(row1) == 1: self._index[:] = row1 + row0 self._offset = 1 return size = 2 ** (int(log(len(row1) - 1, 2)) + 1) row1.extend(repeat(0, size - len(row1))) tree = [row0, row1] while len(tree[-1]) > 1: head = iter(tree[-1]) tail = iter(head) row = list(starmap(add, zip(head, tail))) tree.append(row) reduce(iadd, reversed(tree), self._index) self._offset = size * 2 - 1 def __delitem__(self, index): """Remove value at `index` from sorted list. ``sl.__delitem__(index)`` <==> ``del sl[index]`` Supports slicing. Runtime complexity: `O(log(n))` -- approximate. >>> sl = SortedList('abcde') >>> del sl[2] >>> sl SortedList(['a', 'b', 'd', 'e']) >>> del sl[:2] >>> sl SortedList(['d', 'e']) :param index: integer or slice for indexing :raises IndexError: if index out of range """ if isinstance(index, slice): start, stop, step = index.indices(self._len) if step == 1 and start < stop: if start == 0 and stop == self._len: return self._clear() elif self._len <= 8 * (stop - start): values = self._getitem(slice(None, start)) if stop < self._len: values += self._getitem(slice(stop, None)) self._clear() return self._update(values) indices = range(start, stop, step) # Delete items from greatest index to least so # that the indices remain valid throughout iteration. if step > 0: indices = reversed(indices) _pos, _delete = self._pos, self._delete for index in indices: pos, idx = _pos(index) _delete(pos, idx) else: pos, idx = self._pos(index) self._delete(pos, idx) def __getitem__(self, index): """Lookup value at `index` in sorted list. ``sl.__getitem__(index)`` <==> ``sl[index]`` Supports slicing. Runtime complexity: `O(log(n))` -- approximate. >>> sl = SortedList('abcde') >>> sl[1] 'b' >>> sl[-1] 'e' >>> sl[2:5] ['c', 'd', 'e'] :param index: integer or slice for indexing :return: value or list of values :raises IndexError: if index out of range """ _lists = self._lists if isinstance(index, slice): start, stop, step = index.indices(self._len) if step == 1 and start < stop: if start == 0 and stop == self._len: return reduce(iadd, self._lists, []) start_pos, start_idx = self._pos(start) if stop == self._len: stop_pos = len(_lists) - 1 stop_idx = len(_lists[stop_pos]) else: stop_pos, stop_idx = self._pos(stop) if start_pos == stop_pos: return _lists[start_pos][start_idx:stop_idx] prefix = _lists[start_pos][start_idx:] middle = _lists[(start_pos + 1):stop_pos] result = reduce(iadd, middle, prefix) result += _lists[stop_pos][:stop_idx] return result if step == -1 and start > stop: result = self._getitem(slice(stop + 1, start + 1)) result.reverse() return result # Return a list because a negative step could # reverse the order of the items and this could # be the desired behavior. indices = range(start, stop, step) return list(self._getitem(index) for index in indices) else: if self._len: if index == 0: return _lists[0][0] elif index == -1: return _lists[-1][-1] else: raise IndexError('list index out of range') if 0 <= index < len(_lists[0]): return _lists[0][index] len_last = len(_lists[-1]) if -len_last < index < 0: return _lists[-1][len_last + index] pos, idx = self._pos(index) return _lists[pos][idx] _getitem = __getitem__ def __setitem__(self, index, value): """Raise not-implemented error. ``sl.__setitem__(index, value)`` <==> ``sl[index] = value`` :raises NotImplementedError: use ``del sl[index]`` and ``sl.add(value)`` instead """ message = 'use ``del sl[index]`` and ``sl.add(value)`` instead' raise NotImplementedError(message) def __iter__(self): """Return an iterator over the sorted list. ``sl.__iter__()`` <==> ``iter(sl)`` Iterating the sorted list while adding or deleting values may raise a :exc:`RuntimeError` or fail to iterate over all values. """ return chain.from_iterable(self._lists) def __reversed__(self): """Return a reverse iterator over the sorted list. ``sl.__reversed__()`` <==> ``reversed(sl)`` Iterating the sorted list while adding or deleting values may raise a :exc:`RuntimeError` or fail to iterate over all values. """ return chain.from_iterable(map(reversed, reversed(self._lists))) def reverse(self): """Raise not-implemented error. Sorted list maintains values in ascending sort order. Values may not be reversed in-place. Use ``reversed(sl)`` for an iterator over values in descending sort order. Implemented to override `MutableSequence.reverse` which provides an erroneous default implementation. :raises NotImplementedError: use ``reversed(sl)`` instead """ raise NotImplementedError('use ``reversed(sl)`` instead') def islice(self, start=None, stop=None, reverse=False): """Return an iterator that slices sorted list from `start` to `stop`. The `start` and `stop` index are treated inclusive and exclusive, respectively. Both `start` and `stop` default to `None` which is automatically inclusive of the beginning and end of the sorted list. When `reverse` is `True` the values are yielded from the iterator in reverse order; `reverse` defaults to `False`. >>> sl = SortedList('abcdefghij') >>> it = sl.islice(2, 6) >>> list(it) ['c', 'd', 'e', 'f'] :param int start: start index (inclusive) :param int stop: stop index (exclusive) :param bool reverse: yield values in reverse order :return: iterator """ _len = self._len if not _len: return iter(()) start, stop, _ = slice(start, stop).indices(self._len) if start >= stop: return iter(()) _pos = self._pos min_pos, min_idx = _pos(start) if stop == _len: max_pos = len(self._lists) - 1 max_idx = len(self._lists[-1]) else: max_pos, max_idx = _pos(stop) return self._islice(min_pos, min_idx, max_pos, max_idx, reverse) def _islice(self, min_pos, min_idx, max_pos, max_idx, reverse): """Return an iterator that slices sorted list using two index pairs. The index pairs are (min_pos, min_idx) and (max_pos, max_idx), the first inclusive and the latter exclusive. See `_pos` for details on how an index is converted to an index pair. When `reverse` is `True`, values are yielded from the iterator in reverse order. """ _lists = self._lists if min_pos > max_pos: return iter(()) if min_pos == max_pos: if reverse: indices = reversed(range(min_idx, max_idx)) return map(_lists[min_pos].__getitem__, indices) indices = range(min_idx, max_idx) return map(_lists[min_pos].__getitem__, indices) next_pos = min_pos + 1 if next_pos == max_pos: if reverse: min_indices = range(min_idx, len(_lists[min_pos])) max_indices = range(max_idx) return chain( map(_lists[max_pos].__getitem__, reversed(max_indices)), map(_lists[min_pos].__getitem__, reversed(min_indices)), ) min_indices = range(min_idx, len(_lists[min_pos])) max_indices = range(max_idx) return chain( map(_lists[min_pos].__getitem__, min_indices), map(_lists[max_pos].__getitem__, max_indices), ) if reverse: min_indices = range(min_idx, len(_lists[min_pos])) sublist_indices = range(next_pos, max_pos) sublists = map(_lists.__getitem__, reversed(sublist_indices)) max_indices = range(max_idx) return chain( map(_lists[max_pos].__getitem__, reversed(max_indices)), chain.from_iterable(map(reversed, sublists)), map(_lists[min_pos].__getitem__, reversed(min_indices)), ) min_indices = range(min_idx, len(_lists[min_pos])) sublist_indices = range(next_pos, max_pos) sublists = map(_lists.__getitem__, sublist_indices) max_indices = range(max_idx) return chain( map(_lists[min_pos].__getitem__, min_indices), chain.from_iterable(sublists), map(_lists[max_pos].__getitem__, max_indices), ) def irange(self, minimum=None, maximum=None, inclusive=(True, True), reverse=False): """Create an iterator of values between `minimum` and `maximum`. Both `minimum` and `maximum` default to `None` which is automatically inclusive of the beginning and end of the sorted list. The argument `inclusive` is a pair of booleans that indicates whether the minimum and maximum ought to be included in the range, respectively. The default is ``(True, True)`` such that the range is inclusive of both minimum and maximum. When `reverse` is `True` the values are yielded from the iterator in reverse order; `reverse` defaults to `False`. >>> sl = SortedList('abcdefghij') >>> it = sl.irange('c', 'f') >>> list(it) ['c', 'd', 'e', 'f'] :param minimum: minimum value to start iterating :param maximum: maximum value to stop iterating :param inclusive: pair of booleans :param bool reverse: yield values in reverse order :return: iterator """ _maxes = self._maxes if not _maxes: return iter(()) _lists = self._lists # Calculate the minimum (pos, idx) pair. By default this location # will be inclusive in our calculation. if minimum is None: min_pos = 0 min_idx = 0 else: if inclusive[0]: min_pos = bisect_left(_maxes, minimum) if min_pos == len(_maxes): return iter(()) min_idx = bisect_left(_lists[min_pos], minimum) else: min_pos = bisect_right(_maxes, minimum) if min_pos == len(_maxes): return iter(()) min_idx = bisect_right(_lists[min_pos], minimum) # Calculate the maximum (pos, idx) pair. By default this location # will be exclusive in our calculation. if maximum is None: max_pos = len(_maxes) - 1 max_idx = len(_lists[max_pos]) else: if inclusive[1]: max_pos = bisect_right(_maxes, maximum) if max_pos == len(_maxes): max_pos -= 1 max_idx = len(_lists[max_pos]) else: max_idx = bisect_right(_lists[max_pos], maximum) else: max_pos = bisect_left(_maxes, maximum) if max_pos == len(_maxes): max_pos -= 1 max_idx = len(_lists[max_pos]) else: max_idx = bisect_left(_lists[max_pos], maximum) return self._islice(min_pos, min_idx, max_pos, max_idx, reverse) def __len__(self): """Return the size of the sorted list. ``sl.__len__()`` <==> ``len(sl)`` :return: size of sorted list """ return self._len def bisect_left(self, value): """Return an index to insert `value` in the sorted list. If the `value` is already present, the insertion point will be before (to the left of) any existing values. Similar to the `bisect` module in the standard library. Runtime complexity: `O(log(n))` -- approximate. >>> sl = SortedList([10, 11, 12, 13, 14]) >>> sl.bisect_left(12) 2 :param value: insertion index of value in sorted list :return: index """ _maxes = self._maxes if not _maxes: return 0 pos = bisect_left(_maxes, value) if pos == len(_maxes): return self._len idx = bisect_left(self._lists[pos], value) return self._loc(pos, idx) def bisect_right(self, value): """Return an index to insert `value` in the sorted list. Similar to `bisect_left`, but if `value` is already present, the insertion point with be after (to the right of) any existing values. Similar to the `bisect` module in the standard library. Runtime complexity: `O(log(n))` -- approximate. >>> sl = SortedList([10, 11, 12, 13, 14]) >>> sl.bisect_right(12) 3 :param value: insertion index of value in sorted list :return: index """ _maxes = self._maxes if not _maxes: return 0 pos = bisect_right(_maxes, value) if pos == len(_maxes): return self._len idx = bisect_right(self._lists[pos], value) return self._loc(pos, idx) bisect = bisect_right _bisect_right = bisect_right def count(self, value): """Return number of occurrences of `value` in the sorted list. Runtime complexity: `O(log(n))` -- approximate. >>> sl = SortedList([1, 2, 2, 3, 3, 3, 4, 4, 4, 4]) >>> sl.count(3) 3 :param value: value to count in sorted list :return: count """ _maxes = self._maxes if not _maxes: return 0 pos_left = bisect_left(_maxes, value) if pos_left == len(_maxes): return 0 _lists = self._lists idx_left = bisect_left(_lists[pos_left], value) pos_right = bisect_right(_maxes, value) if pos_right == len(_maxes): return self._len - self._loc(pos_left, idx_left) idx_right = bisect_right(_lists[pos_right], value) if pos_left == pos_right: return idx_right - idx_left right = self._loc(pos_right, idx_right) left = self._loc(pos_left, idx_left) return right - left def copy(self): """Return a shallow copy of the sorted list. Runtime complexity: `O(n)` :return: new sorted list """ return self.__class__(self) __copy__ = copy def append(self, value): """Raise not-implemented error. Implemented to override `MutableSequence.append` which provides an erroneous default implementation. :raises NotImplementedError: use ``sl.add(value)`` instead """ raise NotImplementedError('use ``sl.add(value)`` instead') def extend(self, values): """Raise not-implemented error. Implemented to override `MutableSequence.extend` which provides an erroneous default implementation. :raises NotImplementedError: use ``sl.update(values)`` instead """ raise NotImplementedError('use ``sl.update(values)`` instead') def insert(self, index, value): """Raise not-implemented error. :raises NotImplementedError: use ``sl.add(value)`` instead """ raise NotImplementedError('use ``sl.add(value)`` instead') def pop(self, index=-1): """Remove and return value at `index` in sorted list. Raise :exc:`IndexError` if the sorted list is empty or index is out of range. Negative indices are supported. Runtime complexity: `O(log(n))` -- approximate. >>> sl = SortedList('abcde') >>> sl.pop() 'e' >>> sl.pop(2) 'c' >>> sl SortedList(['a', 'b', 'd']) :param int index: index of value (default -1) :return: value :raises IndexError: if index is out of range """ if not self._len: raise IndexError('pop index out of range') _lists = self._lists if index == 0: val = _lists[0][0] self._delete(0, 0) return val if index == -1: pos = len(_lists) - 1 loc = len(_lists[pos]) - 1 val = _lists[pos][loc] self._delete(pos, loc) return val if 0 <= index < len(_lists[0]): val = _lists[0][index] self._delete(0, index) return val len_last = len(_lists[-1]) if -len_last < index < 0: pos = len(_lists) - 1 loc = len_last + index val = _lists[pos][loc] self._delete(pos, loc) return val pos, idx = self._pos(index) val = _lists[pos][idx] self._delete(pos, idx) return val def index(self, value, start=None, stop=None): """Return first index of value in sorted list. Raise ValueError if `value` is not present. Index must be between `start` and `stop` for the `value` to be considered present. The default value, None, for `start` and `stop` indicate the beginning and end of the sorted list. Negative indices are supported. Runtime complexity: `O(log(n))` -- approximate. >>> sl = SortedList('abcde') >>> sl.index('d') 3 >>> sl.index('z') Traceback (most recent call last): ... ValueError: 'z' is not in list :param value: value in sorted list :param int start: start index (default None, start of sorted list) :param int stop: stop index (default None, end of sorted list) :return: index of value :raises ValueError: if value is not present """ _len = self._len if not _len: raise ValueError('{0!r} is not in list'.format(value)) if start is None: start = 0 if start < 0: start += _len if start < 0: start = 0 if stop is None: stop = _len if stop < 0: stop += _len if stop > _len: stop = _len if stop <= start: raise ValueError('{0!r} is not in list'.format(value)) _maxes = self._maxes pos_left = bisect_left(_maxes, value) if pos_left == len(_maxes): raise ValueError('{0!r} is not in list'.format(value)) _lists = self._lists idx_left = bisect_left(_lists[pos_left], value) if _lists[pos_left][idx_left] != value: raise ValueError('{0!r} is not in list'.format(value)) stop -= 1 left = self._loc(pos_left, idx_left) if start <= left: if left <= stop: return left else: right = self._bisect_right(value) - 1 if start <= right: return start raise ValueError('{0!r} is not in list'.format(value)) def __add__(self, other): """Return new sorted list containing all values in both sequences. ``sl.__add__(other)`` <==> ``sl + other`` Values in `other` do not need to be in sorted order. Runtime complexity: `O(n*log(n))` >>> sl1 = SortedList('bat') >>> sl2 = SortedList('cat') >>> sl1 + sl2 SortedList(['a', 'a', 'b', 'c', 't', 't']) :param other: other iterable :return: new sorted list """ values = reduce(iadd, self._lists, []) values.extend(other) return self.__class__(values) __radd__ = __add__ def __iadd__(self, other): """Update sorted list with values from `other`. ``sl.__iadd__(other)`` <==> ``sl += other`` Values in `other` do not need to be in sorted order. Runtime complexity: `O(k*log(n))` -- approximate. >>> sl = SortedList('bat') >>> sl += 'cat' >>> sl SortedList(['a', 'a', 'b', 'c', 't', 't']) :param other: other iterable :return: existing sorted list """ self._update(other) return self def __mul__(self, num): """Return new sorted list with `num` shallow copies of values. ``sl.__mul__(num)`` <==> ``sl * num`` Runtime complexity: `O(n*log(n))` >>> sl = SortedList('abc') >>> sl * 3 SortedList(['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c']) :param int num: count of shallow copies :return: new sorted list """ values = reduce(iadd, self._lists, []) * num return self.__class__(values) __rmul__ = __mul__ def __imul__(self, num): """Update the sorted list with `num` shallow copies of values. ``sl.__imul__(num)`` <==> ``sl *= num`` Runtime complexity: `O(n*log(n))` >>> sl = SortedList('abc') >>> sl *= 3 >>> sl SortedList(['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c']) :param int num: count of shallow copies :return: existing sorted list """ values = reduce(iadd, self._lists, []) * num self._clear() self._update(values) return self def __make_cmp(seq_op, symbol, doc): "Make comparator method." def comparer(self, other): "Compare method for sorted list and sequence." if not isinstance(other, Sequence): return NotImplemented self_len = self._len len_other = len(other) if self_len != len_other: if seq_op is eq: return False if seq_op is ne: return True for alpha, beta in zip(self, other): if alpha != beta: return seq_op(alpha, beta) return seq_op(self_len, len_other) seq_op_name = seq_op.__name__ comparer.__name__ = '__{0}__'.format(seq_op_name) doc_str = """Return true if and only if sorted list is {0} `other`. ``sl.__{1}__(other)`` <==> ``sl {2} other`` Comparisons use lexicographical order as with sequences. Runtime complexity: `O(n)` :param other: `other` sequence :return: true if sorted list is {0} `other` """ comparer.__doc__ = dedent(doc_str.format(doc, seq_op_name, symbol)) return comparer __eq__ = __make_cmp(eq, '==', 'equal to') __ne__ = __make_cmp(ne, '!=', 'not equal to') __lt__ = __make_cmp(lt, '<', 'less than') __gt__ = __make_cmp(gt, '>', 'greater than') __le__ = __make_cmp(le, '<=', 'less than or equal to') __ge__ = __make_cmp(ge, '>=', 'greater than or equal to') __make_cmp = staticmethod(__make_cmp) @recursive_repr() def __repr__(self): """Return string representation of sorted list. ``sl.__repr__()`` <==> ``repr(sl)`` :return: string representation """ return '{0}({1!r})'.format(type(self).__name__, list(self)) def _check(self): """Check invariants of sorted list. Runtime complexity: `O(n)` """ try: assert self._load >= 4 assert len(self._maxes) == len(self._lists) assert self._len == sum(len(sublist) for sublist in self._lists) # Check all sublists are sorted. for sublist in self._lists: for pos in range(1, len(sublist)): assert sublist[pos - 1] <= sublist[pos] # Check beginning/end of sublists are sorted. for pos in range(1, len(self._lists)): assert self._lists[pos - 1][-1] <= self._lists[pos][0] # Check _maxes index is the last value of each sublist. for pos in range(len(self._maxes)): assert self._maxes[pos] == self._lists[pos][-1] # Check sublist lengths are less than double load-factor. double = self._load << 1 assert all(len(sublist) <= double for sublist in self._lists) # Check sublist lengths are greater than half load-factor for all # but the last sublist. half = self._load >> 1 for pos in range(0, len(self._lists) - 1): assert len(self._lists[pos]) >= half if self._index: assert self._len == self._index[0] assert len(self._index) == self._offset + len(self._lists) # Check index leaf nodes equal length of sublists. for pos in range(len(self._lists)): leaf = self._index[self._offset + pos] assert leaf == len(self._lists[pos]) # Check index branch nodes are the sum of their children. for pos in range(self._offset): child = (pos << 1) + 1 if child >= len(self._index): assert self._index[pos] == 0 elif child + 1 == len(self._index): assert self._index[pos] == self._index[child] else: child_sum = self._index[child] + self._index[child + 1] assert child_sum == self._index[pos] except: import sys import traceback traceback.print_exc(file=sys.stdout) print('len', self._len) print('load', self._load) print('offset', self._offset) print('len_index', len(self._index)) print('index', self._index) print('len_maxes', len(self._maxes)) print('maxes', self._maxes) print('len_lists', len(self._lists)) print('lists', self._lists) raise def identity(value): "Identity function." return value n, d, k = map(int, input().split()) if d >= n: print('NO') else: deg = [0] * n ans = [] free = SortedList() for i in range(d): deg[i] += 1 deg[i + 1] += 1 if deg[i] > k or deg[i + 1] > k: print("NO") exit() ans.append((i, i + 1)) for i in range(1, d): free.add((max(i, d - i), i)) for i in range(d + 1, n): while len(free) > 0 and deg[free[0][1]] == k: free.pop(0) if len(free) == 0 or free[0][0] == d: print('NO') exit() deg[i] += 1 deg[free[0][1]] += 1 ans.append((i, free[0][1])) free.add((free[0][0] + 1, i)) print('YES') for elem in ans: print(elem[0] + 1, elem[1] + 1) ```
instruction
0
104,430
13
208,860
Yes
output
1
104,430
13
208,861
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given three integers n, d and k. Your task is to construct an undirected tree on n vertices with diameter d and degree of each vertex at most k, or say that it is impossible. An undirected tree is a connected undirected graph with n - 1 edges. Diameter of a tree is the maximum length of a simple path (a path in which each vertex appears at most once) between all pairs of vertices of this tree. Degree of a vertex is the number of edges incident to this vertex (i.e. for a vertex u it is the number of edges (u, v) that belong to the tree, where v is any other vertex of a tree). Input The first line of the input contains three integers n, d and k (1 ≤ n, d, k ≤ 4 ⋅ 10^5). Output If there is no tree satisfying the conditions above, print only one word "NO" (without quotes). Otherwise in the first line print "YES" (without quotes), and then print n - 1 lines describing edges of a tree satisfying the conditions above. Vertices of the tree must be numbered from 1 to n. You can print edges and vertices connected by an edge in any order. If there are multiple answers, print any of them.1 Examples Input 6 3 3 Output YES 3 1 4 1 1 2 5 2 2 6 Input 6 2 3 Output NO Input 10 4 3 Output YES 2 9 2 10 10 3 3 1 6 10 8 2 4 3 5 6 6 7 Input 8 5 3 Output YES 2 5 7 2 3 7 3 1 1 6 8 7 4 3 Submitted Solution: ``` def construct_tree(n,d, k): nodes = [] edges = [] if d > n - 1: return None if k == 1 and n > 2: return None for i in range(1, d+2): current_deg = k - 1 if i == 1 or i == d + 1 else k - 2 current_depth = min(i-1, d-i+1) if current_depth and current_deg: nodes.append([i, min(i-1, d-i+1), current_deg]) if i < d + 1: edges.append([i, i+1]) current_nodes_count = d + 2 pos = 0 while current_nodes_count < n + 1: if pos >= len(nodes): return None current = nodes[pos] if not current[2]: pos += 1 if pos == len(nodes): break continue if current[1] - 1 and k - 1: nodes.append([current_nodes_count, current[1] - 1, k - 1]) edges.append([current[0], current_nodes_count]) current[2] -= 1 current_nodes_count += 1 if current_nodes_count == n + 1: return edges return None n, d, k = [int(val) for val in input().split()] edges = construct_tree(n, d, k) if edges: print('YES') print('\n'.join(['{0} {1}'.format(e[0], e[1]) for e in edges])) else: print('NO') ```
instruction
0
104,431
13
208,862
Yes
output
1
104,431
13
208,863
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given three integers n, d and k. Your task is to construct an undirected tree on n vertices with diameter d and degree of each vertex at most k, or say that it is impossible. An undirected tree is a connected undirected graph with n - 1 edges. Diameter of a tree is the maximum length of a simple path (a path in which each vertex appears at most once) between all pairs of vertices of this tree. Degree of a vertex is the number of edges incident to this vertex (i.e. for a vertex u it is the number of edges (u, v) that belong to the tree, where v is any other vertex of a tree). Input The first line of the input contains three integers n, d and k (1 ≤ n, d, k ≤ 4 ⋅ 10^5). Output If there is no tree satisfying the conditions above, print only one word "NO" (without quotes). Otherwise in the first line print "YES" (without quotes), and then print n - 1 lines describing edges of a tree satisfying the conditions above. Vertices of the tree must be numbered from 1 to n. You can print edges and vertices connected by an edge in any order. If there are multiple answers, print any of them.1 Examples Input 6 3 3 Output YES 3 1 4 1 1 2 5 2 2 6 Input 6 2 3 Output NO Input 10 4 3 Output YES 2 9 2 10 10 3 3 1 6 10 8 2 4 3 5 6 6 7 Input 8 5 3 Output YES 2 5 7 2 3 7 3 1 1 6 8 7 4 3 Submitted Solution: ``` def main(): n, d, k = map(int, input().split()) _min = d+1 if n < _min: print('NO') else: res = [] deg = [0] * (n+1) dist = [0] * (n+1) stack = [] deg[1] = 1 for i in range(1, d+1): res.append((i, i+1)) if i > 1: deg[i] += 2 dist[i] = max(i-1, d+1-i) dist[d+1] = d deg[d+1] = 1 for i in range(2, d+1): stack.append(i) next = d+2 while stack: if next > n: break v = stack.pop() if dist[v] < d: while next <= n and deg[v] < k: res.append((v, next)) deg[v] += 1 deg[next] += 1 dist[next] = dist[v] + 1 if dist[next] < d: stack.append(next) next += 1 ok = next > n ok &= all(deg[i] <= k for i in range(1, n+1)) ok &= all(dist[i] <= d for i in range(1, n+1)) if not ok: print('NO') else: print('YES') for e in res: print(*e) if __name__ == '__main__': main() ```
instruction
0
104,432
13
208,864
Yes
output
1
104,432
13
208,865
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given three integers n, d and k. Your task is to construct an undirected tree on n vertices with diameter d and degree of each vertex at most k, or say that it is impossible. An undirected tree is a connected undirected graph with n - 1 edges. Diameter of a tree is the maximum length of a simple path (a path in which each vertex appears at most once) between all pairs of vertices of this tree. Degree of a vertex is the number of edges incident to this vertex (i.e. for a vertex u it is the number of edges (u, v) that belong to the tree, where v is any other vertex of a tree). Input The first line of the input contains three integers n, d and k (1 ≤ n, d, k ≤ 4 ⋅ 10^5). Output If there is no tree satisfying the conditions above, print only one word "NO" (without quotes). Otherwise in the first line print "YES" (without quotes), and then print n - 1 lines describing edges of a tree satisfying the conditions above. Vertices of the tree must be numbered from 1 to n. You can print edges and vertices connected by an edge in any order. If there are multiple answers, print any of them.1 Examples Input 6 3 3 Output YES 3 1 4 1 1 2 5 2 2 6 Input 6 2 3 Output NO Input 10 4 3 Output YES 2 9 2 10 10 3 3 1 6 10 8 2 4 3 5 6 6 7 Input 8 5 3 Output YES 2 5 7 2 3 7 3 1 1 6 8 7 4 3 Submitted Solution: ``` def main(): n, d, k = map(int, input().split()) if n < d+1 or d > 1 and k == 1: print('NO') return edges = [(1, 2)] stack = [] d2 = d/2 d21 = d2+1 for node in range(2, d+1): edges.append((node, node+1)) stack.append([node, d2-abs(d21 - node), k-2]) next_i = d+2 while next_i <= n: if not stack: print('NO') return node = stack[-1] i, remaining_depth, remaining_degree = node if remaining_depth == 0 or remaining_degree == 0: stack.pop() continue node[2] -= 1 edges.append((i, next_i)) stack.append([next_i, remaining_depth-1, k-1]) next_i += 1 print('YES') print('\n'.join('{} {}'.format(a, b) for a, b in edges)) main() ```
instruction
0
104,433
13
208,866
Yes
output
1
104,433
13
208,867
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given three integers n, d and k. Your task is to construct an undirected tree on n vertices with diameter d and degree of each vertex at most k, or say that it is impossible. An undirected tree is a connected undirected graph with n - 1 edges. Diameter of a tree is the maximum length of a simple path (a path in which each vertex appears at most once) between all pairs of vertices of this tree. Degree of a vertex is the number of edges incident to this vertex (i.e. for a vertex u it is the number of edges (u, v) that belong to the tree, where v is any other vertex of a tree). Input The first line of the input contains three integers n, d and k (1 ≤ n, d, k ≤ 4 ⋅ 10^5). Output If there is no tree satisfying the conditions above, print only one word "NO" (without quotes). Otherwise in the first line print "YES" (without quotes), and then print n - 1 lines describing edges of a tree satisfying the conditions above. Vertices of the tree must be numbered from 1 to n. You can print edges and vertices connected by an edge in any order. If there are multiple answers, print any of them.1 Examples Input 6 3 3 Output YES 3 1 4 1 1 2 5 2 2 6 Input 6 2 3 Output NO Input 10 4 3 Output YES 2 9 2 10 10 3 3 1 6 10 8 2 4 3 5 6 6 7 Input 8 5 3 Output YES 2 5 7 2 3 7 3 1 1 6 8 7 4 3 Submitted Solution: ``` n, d, k = map(int, input().split()) if n==8 and d==5 and k==3: print('YES') print('2 5') print('7 2') print('3 7') print('3 1') print('1 6') print('8 7') print('4 3') exit() elif (n,d,k) == (5,4,3): print('YES') print('5 2') print('4 2') print('3 4') print('1 3') exit() output = [] queue = [] n -= 1 for i in range(min(k, n)): output.append('{0} {1}'.format(1, i+2)) queue.append((i+2, 1)) nxt = min(k, n)+2 n -= min(k, n) prevdpt = 0 more = False dpt = 0 while n > 0: x, dpt = queue.pop(0) if prevdpt == dpt: more = True prevdpt = dpt for i in range(min(k-1, n)): output.append('{0} {1}'.format(x, nxt)) queue.append((nxt, dpt+1)) nxt += 1 n -= 1 dpt += 1 dpt *= 2 if not more: dpt -= 1 if dpt <= d: print('YES') for o in output: print(o) else: print('NO') ```
instruction
0
104,434
13
208,868
No
output
1
104,434
13
208,869
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given three integers n, d and k. Your task is to construct an undirected tree on n vertices with diameter d and degree of each vertex at most k, or say that it is impossible. An undirected tree is a connected undirected graph with n - 1 edges. Diameter of a tree is the maximum length of a simple path (a path in which each vertex appears at most once) between all pairs of vertices of this tree. Degree of a vertex is the number of edges incident to this vertex (i.e. for a vertex u it is the number of edges (u, v) that belong to the tree, where v is any other vertex of a tree). Input The first line of the input contains three integers n, d and k (1 ≤ n, d, k ≤ 4 ⋅ 10^5). Output If there is no tree satisfying the conditions above, print only one word "NO" (without quotes). Otherwise in the first line print "YES" (without quotes), and then print n - 1 lines describing edges of a tree satisfying the conditions above. Vertices of the tree must be numbered from 1 to n. You can print edges and vertices connected by an edge in any order. If there are multiple answers, print any of them.1 Examples Input 6 3 3 Output YES 3 1 4 1 1 2 5 2 2 6 Input 6 2 3 Output NO Input 10 4 3 Output YES 2 9 2 10 10 3 3 1 6 10 8 2 4 3 5 6 6 7 Input 8 5 3 Output YES 2 5 7 2 3 7 3 1 1 6 8 7 4 3 Submitted Solution: ``` def construct_tree(n,d, k): nodes = [] edges = [] if d > n - 1: return None if k == 1 and n > 2: return None for i in range(1, d+2): current_deg = k - 1 if i == 1 or i == d + 1 else k - 2 current_depth = min(i-1, d-i+1) if current_depth and current_deg: nodes.append([i, min(i-1, d-i+1), current_deg]) if i < d + 1: edges.append([i, i+1]) current_nodes_count = d + 2 pos = 0 while current_nodes_count < n: current = nodes[pos] if not current[2]: pos += 1 if pos == len(nodes): break continue if current[1] - 1 and k - 1: nodes.append([current_nodes_count, current[1] - 1, k - 1]) edges.append([current[0], current_nodes_count]) current[2] -= 1 current_nodes_count += 1 if current_nodes_count == n: return edges return None n, d, k = [int(val) for val in input().split()] edges = construct_tree(n, d, k) if edges: print('YES') print('\n'.join(['{0} {1}'.format(e[0], e[1]) for e in edges])) else: print('NO') ```
instruction
0
104,435
13
208,870
No
output
1
104,435
13
208,871
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given three integers n, d and k. Your task is to construct an undirected tree on n vertices with diameter d and degree of each vertex at most k, or say that it is impossible. An undirected tree is a connected undirected graph with n - 1 edges. Diameter of a tree is the maximum length of a simple path (a path in which each vertex appears at most once) between all pairs of vertices of this tree. Degree of a vertex is the number of edges incident to this vertex (i.e. for a vertex u it is the number of edges (u, v) that belong to the tree, where v is any other vertex of a tree). Input The first line of the input contains three integers n, d and k (1 ≤ n, d, k ≤ 4 ⋅ 10^5). Output If there is no tree satisfying the conditions above, print only one word "NO" (without quotes). Otherwise in the first line print "YES" (without quotes), and then print n - 1 lines describing edges of a tree satisfying the conditions above. Vertices of the tree must be numbered from 1 to n. You can print edges and vertices connected by an edge in any order. If there are multiple answers, print any of them.1 Examples Input 6 3 3 Output YES 3 1 4 1 1 2 5 2 2 6 Input 6 2 3 Output NO Input 10 4 3 Output YES 2 9 2 10 10 3 3 1 6 10 8 2 4 3 5 6 6 7 Input 8 5 3 Output YES 2 5 7 2 3 7 3 1 1 6 8 7 4 3 Submitted Solution: ``` def main(): n, d, k = map(int, input().split()) _min = d+1 if n < _min: print('NO') else: res = [] deg = [0] * (n+1) dist = [0] * (n+1) stack = [] deg[1] = 1 for i in range(1, d+1): res.append((i, i+1)) if i > 1: deg[i] += 2 dist[i] = max(i-1, d+1-i) dist[d+1] = d deg[d+1] = 1 for i in range(2, d+1): stack.append(i) next = d+2 while stack: if next > n: break v = stack.pop() if dist[v] < d: while next <= n and deg[v] < k: res.append((v, next)) deg[v] += 1 deg[next] += 1 dist[next] = dist[v] + 1 if dist[next] < d: stack.append(next) next += 1 if next <= n: print('NO') else: print('YES') for e in res: print(*e) if __name__ == '__main__': main() ```
instruction
0
104,436
13
208,872
No
output
1
104,436
13
208,873
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given three integers n, d and k. Your task is to construct an undirected tree on n vertices with diameter d and degree of each vertex at most k, or say that it is impossible. An undirected tree is a connected undirected graph with n - 1 edges. Diameter of a tree is the maximum length of a simple path (a path in which each vertex appears at most once) between all pairs of vertices of this tree. Degree of a vertex is the number of edges incident to this vertex (i.e. for a vertex u it is the number of edges (u, v) that belong to the tree, where v is any other vertex of a tree). Input The first line of the input contains three integers n, d and k (1 ≤ n, d, k ≤ 4 ⋅ 10^5). Output If there is no tree satisfying the conditions above, print only one word "NO" (without quotes). Otherwise in the first line print "YES" (without quotes), and then print n - 1 lines describing edges of a tree satisfying the conditions above. Vertices of the tree must be numbered from 1 to n. You can print edges and vertices connected by an edge in any order. If there are multiple answers, print any of them.1 Examples Input 6 3 3 Output YES 3 1 4 1 1 2 5 2 2 6 Input 6 2 3 Output NO Input 10 4 3 Output YES 2 9 2 10 10 3 3 1 6 10 8 2 4 3 5 6 6 7 Input 8 5 3 Output YES 2 5 7 2 3 7 3 1 1 6 8 7 4 3 Submitted Solution: ``` def main(): n, d, k = map(int, input().split()) if n < d+1: print('NO') return edges = [(1, 2)] stack = [] d2 = d/2 d21 = d2+1 for node in range(2, d+1): edges.append((node, node+1)) stack.append([node, d2-abs(d21 - node), k-2]) next_i = d+2 while next_i <= n: if not stack: print('NO') return node = stack[-1] i, remaining_depth, remaining_degree = node if remaining_depth == 0 or remaining_degree == 0: stack.pop() continue node[2] -= 1 edges.append((i, next_i)) stack.append([next_i, remaining_depth-1, k-1]) next_i += 1 print('YES') print('\n'.join('{} {}'.format(a, b) for a, b in edges)) main() ```
instruction
0
104,437
13
208,874
No
output
1
104,437
13
208,875
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Let's define the Eulerian traversal of a tree (a connected undirected graph without cycles) as follows: consider a depth-first search algorithm which traverses vertices of the tree and enumerates them in the order of visiting (only the first visit of each vertex counts). This function starts from the vertex number 1 and then recursively runs from all vertices which are connected with an edge with the current vertex and are not yet visited in increasing numbers order. Formally, you can describe this function using the following pseudocode: next_id = 1 id = array of length n filled with -1 visited = array of length n filled with false function dfs(v): visited[v] = true id[v] = next_id next_id += 1 for to in neighbors of v in increasing order: if not visited[to]: dfs(to) You are given a weighted tree, the vertices of which were enumerated with integers from 1 to n using the algorithm described above. A leaf is a vertex of the tree which is connected with only one other vertex. In the tree given to you, the vertex 1 is not a leaf. The distance between two vertices in the tree is the sum of weights of the edges on the simple path between them. You have to answer q queries of the following type: given integers v, l and r, find the shortest distance from vertex v to one of the leaves with indices from l to r inclusive. Input The first line contains two integers n and q (3 ≤ n ≤ 500 000, 1 ≤ q ≤ 500 000) — the number of vertices in the tree and the number of queries, respectively. The (i - 1)-th of the following n - 1 lines contains two integers p_i and w_i (1 ≤ p_i < i, 1 ≤ w_i ≤ 10^9), denoting an edge between vertices p_i and i with the weight w_i. It's guaranteed that the given edges form a tree and the vertices are enumerated in the Eulerian traversal order and that the vertex with index 1 is not a leaf. The next q lines describe the queries. Each of them contains three integers v_i, l_i, r_i (1 ≤ v_i ≤ n, 1 ≤ l_i ≤ r_i ≤ n), describing the parameters of the query. It is guaranteed that there is at least one leaf with index x such that l_i ≤ x ≤ r_i. Output Output q integers — the answers for the queries in the order they are given in the input. Examples Input 5 3 1 10 1 1 3 2 3 3 1 1 5 5 4 5 4 1 2 Output 3 0 13 Input 5 3 1 1000000000 2 1000000000 1 1000000000 1 1000000000 3 4 5 2 1 5 2 4 5 Output 3000000000 1000000000 2000000000 Input 11 8 1 7 2 1 1 20 1 2 5 6 6 2 6 3 5 1 9 10 9 11 5 1 11 1 1 4 9 4 8 6 1 4 9 7 11 9 10 11 8 1 11 11 4 5 Output 8 8 9 16 9 10 0 34 Note In the first example, the tree looks like this: <image> In the first query, the nearest leaf for the vertex 1 is vertex 4 with distance 3. In the second query, the nearest leaf for vertex 5 is vertex 5 with distance 0. In the third query the nearest leaf for vertex 4 is vertex 4; however, it is not inside interval [1, 2] of the query. The only leaf in interval [1, 2] is vertex 2 with distance 13 from vertex 4. Submitted Solution: ``` n, q = map(int, input().split()) children = [[]] * (n+1) upiti = [[]] * (n+1) hi = [0] * (n+1) dub = [0] * (n+1) ans = [10**18] * q class Segmentno: def __init__(self): self.a = [0] * (2 * 524288) self.b = [0] * (2 * 524288) def push(self, x): if x < 524288: self.b[2*x] += self.b[x] self.b[2*x + 1] += self.b[x] self.a[x] += self.b[x] self.b[x] = 0 def update_impl(self, l, r, v, x, xl, xr): if r < xl or xr < l: self.push(x) return if l <= xl and xr <= r: self.b[x] += v self.push(x) return xm = (xl + xr) // 2 self.push(x) self.update_impl(l, r, v, 2*x, xl, xm) self.update_impl(l, r, v, 2*x+1, xm+1, xr) self.a[x] = min(self.a[2*x:2*x+2]) def update(self, l, r, v): self.update_impl(l, r, v, 1, 1, 524288) def get_impl(self, l, r, x, xl, xr): self.push(x) if r < xl or xr < l: return 10 ** 18 if l <= xl and xr <= r: return self.a[x] xm = (xl + xr) // 2 return min([ self.get_impl(l, r, 2*x, xl, xm), self.get_impl(l, r, 2*x+1, xm+1, xr) ]) def get(self, l, r): return self.get_impl(l, r, 1, 1, 524288) for i in range(2, n+1): p, w = map(int, input().split()) if children[p] == []: children[p] = [] children[p] += [(i, w)] drvo = Segmentno() def calc_hi(x): hi[x] = x for y, w in children[x]: dub[y] = dub[x] + w calc_hi(y) hi[x] = hi[y] calc_hi(1) for i in range(1, n+1): print(children[i]) if len(children[i]) > 0: drvo.update(i, i, 10**18) else: drvo.update(i, i, dub[i]) for i in range(q): x, l, r = map(int, input().split()) if upiti[x] == []: upiti[x] = [] upiti[x] += [(l, r, i)] def dfs(x): for l, r, i in upiti[x]: ans[i] = drvo.get(l, r) for y, w in children[x]: drvo.update(1, n, w) drvo.update(y, hi[y], -w-w) dfs(y) drvo.update(y, hi[y], w+w) drvo.update(1, n, -w) dfs(1) for x in ans: print(x) ```
instruction
0
104,454
13
208,908
No
output
1
104,454
13
208,909
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. I'm the Map, I'm the Map! I'm the MAP!!! Map In anticipation of new adventures Boots wanted to do a good deed. After discussion with the Map and Backpack, they decided to gift Dora a connected graph. After a long search, Boots chose t graph's variants, which Dora might like. However fox Swiper wants to spoil his plan. The Swiper knows, that Dora now is only able to count up to 3, so he has came up with a following idea. He wants to steal some non-empty set of vertices, so that the Dora won't notice the loss. He has decided to steal some non-empty set of vertices, so that after deletion of the stolen vertices and edges adjacent to them, every remaining vertex wouldn't change it's degree modulo 3. The degree of a vertex is the number of edges it is adjacent to. It would've been suspicious to steal all the vertices, so Swiper needs another plan. Boots are sure, that the crime can not be allowed. However they are afraid, that they won't be able to handle this alone. So Boots decided to ask for your help. Please determine for every graph's variant whether the Swiper can perform the theft or not. Input The first line contains a single integer t (1 ≤ t ≤ 100 000) — the number of graph variants. The first line of each variant contains integers n, m (1 ≤ n ≤ 500 000, 0 ≤ m ≤ 500 000), the number of vertexes and edges in the graph. Then m lines follow, each containing integers a_i, b_i (1 ≤ a_i, b_i ≤ n), the indices of the vertices connected with a corresponding edge. It's guaranteed, that the graph is connected and doesn't contain multiple edges or self-loops. It's guaranteed, that the sum of n over all variants is at most 500 000 and that the sum of m over all variants is at most 500 000. Descriptions of graph's variants are separated with an empty line. Output For each variant: * In case the answer exists, print "Yes" and then the answer itself. The first line should contain an integer c (1 < c < n), the number of vertices the Crook can steal, without Dora noticing the loss. On the next line print c distinct integers, the indices of the graph's vertices in arbitrary order. * Otherwise print "No". In case there are several correct ways to steal the vertices, print any of them. Please note, that it's not required to maximize the number of stolen vertices. Example Input 3 3 3 1 2 2 3 3 1 6 6 1 2 1 3 2 3 2 5 2 6 2 4 8 12 1 2 1 3 2 3 1 4 4 5 5 1 3 6 3 7 3 8 6 1 7 1 8 1 Output No Yes 3 4 5 6 Yes 3 6 7 8 Note The picture below shows the third variant from the example test. The set of the vertices the Crook can steal is denoted with bold. <image> Submitted Solution: ``` from collections import deque from typing import List N = 500005 visited = [False] * N good = [False] * N parent = [0] * N h = [0] * N adj: List[List[int]] = [[] for _ in range(N)] q = deque() degree = [0] * N def dfs1(u: int): mx = -1 visited[u] = True for v in adj[u]: if visited[v] and h[v] < h[u] - 1 and (mx == -1 or h[v] > h[mx]): mx = v if mx != -1 and h[u] - h[mx] + 1 < n and degree[mx] % 3 > 1: while u != parent[mx]: good[u] = True u = parent[u] return True for v in adj[u]: if not visited[v]: parent[v] = u h[v] = h[u] + 1 if dfs1(v): return True return False def dfs2(u: int): visited[u] = True for v in adj[u]: if not visited[v]: dfs2(v) def has_3k_vertex(): for i in range(n): if degree[i] % 3 == 0: good[i] = True return True return False def has_121_path(): parent[root] = -1 visited[root] = True q.append(root) while len(q): u = q.popleft() if u != root and degree[u] % 3 == 1 and h[u] < n - 1: while u != -1: good[u] = True u = parent[u] q.clear() return True for v in adj[u]: if not visited[v]: visited[v] = True q.append(v) parent[v] = u h[v] = h[u] + 1 q.popleft() def has_2_cycle(): parent[root if root < n else 0] = -1 for i in range(n): visited[i] = False return dfs1(root if root < n else 0) def has_122_components(): flag = False for i in range(n): visited[i] = False visited[root] = good[root] = True # adj[root].sort(key=lambda a: h[a]) for u in adj[root]: if not visited[u] and h[u] > 1: v = u good[u] = True while parent[v] != root: v = parent[v] good[v] = True if flag: break dfs2(v) flag = True return True if __name__ == '__main__': s = int(input()) while s > 0: n, m = [int(a) for a in input().split(' ')] for i in range(m): u, v = [int(a) - 1 for a in input().split(' ')] degree[u] += 1 degree[v] += 1 adj[u].append(v) adj[v].append(u) v1 = [a for a in range(n) if degree[a] % 3 == 1] root = v1[0] if len(v1) > 0 else n if has_3k_vertex() or (len(v1) > 1 and has_121_path()) or has_2_cycle() or\ (root < n and degree[root] > 4 and has_122_components()): li = list() for i in range(n): if not good[i]: li.append(str(i + 1)) print("Yes") print(len(li)) print(' '.join(li)) else: print('No') for i in range(n): adj[i].clear() visited[i] = good[i] = False parent[i] = degree[i] = h[i] = 0 s -= 1 if s != 0: input() ```
instruction
0
104,519
13
209,038
No
output
1
104,519
13
209,039
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. I'm the Map, I'm the Map! I'm the MAP!!! Map In anticipation of new adventures Boots wanted to do a good deed. After discussion with the Map and Backpack, they decided to gift Dora a connected graph. After a long search, Boots chose t graph's variants, which Dora might like. However fox Swiper wants to spoil his plan. The Swiper knows, that Dora now is only able to count up to 3, so he has came up with a following idea. He wants to steal some non-empty set of vertices, so that the Dora won't notice the loss. He has decided to steal some non-empty set of vertices, so that after deletion of the stolen vertices and edges adjacent to them, every remaining vertex wouldn't change it's degree modulo 3. The degree of a vertex is the number of edges it is adjacent to. It would've been suspicious to steal all the vertices, so Swiper needs another plan. Boots are sure, that the crime can not be allowed. However they are afraid, that they won't be able to handle this alone. So Boots decided to ask for your help. Please determine for every graph's variant whether the Swiper can perform the theft or not. Input The first line contains a single integer t (1 ≤ t ≤ 100 000) — the number of graph variants. The first line of each variant contains integers n, m (1 ≤ n ≤ 500 000, 0 ≤ m ≤ 500 000), the number of vertexes and edges in the graph. Then m lines follow, each containing integers a_i, b_i (1 ≤ a_i, b_i ≤ n), the indices of the vertices connected with a corresponding edge. It's guaranteed, that the graph is connected and doesn't contain multiple edges or self-loops. It's guaranteed, that the sum of n over all variants is at most 500 000 and that the sum of m over all variants is at most 500 000. Descriptions of graph's variants are separated with an empty line. Output For each variant: * In case the answer exists, print "Yes" and then the answer itself. The first line should contain an integer c (1 < c < n), the number of vertices the Crook can steal, without Dora noticing the loss. On the next line print c distinct integers, the indices of the graph's vertices in arbitrary order. * Otherwise print "No". In case there are several correct ways to steal the vertices, print any of them. Please note, that it's not required to maximize the number of stolen vertices. Example Input 3 3 3 1 2 2 3 3 1 6 6 1 2 1 3 2 3 2 5 2 6 2 4 8 12 1 2 1 3 2 3 1 4 4 5 5 1 3 6 3 7 3 8 6 1 7 1 8 1 Output No Yes 3 4 5 6 Yes 3 6 7 8 Note The picture below shows the third variant from the example test. The set of the vertices the Crook can steal is denoted with bold. <image> Submitted Solution: ``` upper,lower,n,m = 0,0,0,0 graph = [] deg = [] depth = [] parent = [] q = [] pred = [] keep = [] mod = [] def dfs(v): global lower global upper r = 0 for u in graph[v]: if parent[v] != u and deg[u] % 3 == 2: if depth[u]: lower = lower if lower else v upper = upper if upper else u r = 1 else: depth[u] = depth[v] + 1 parent[u] = v r |= dfs(u) return r def forest(): r = 1 for v in mod[2]: if depth[v] == 0: parent[v] = -1 depth[v] = 1 if dfs(v): r = 0 return r def answer(): keep.sort() if len(keep) == n: print("No") else: #devolver todos los vértices que van a ser robados, #que sería aquellos que no pertenecen al conjunto keep. print("Yes") print(n - len(keep)) k = n - len(keep) i = 1 j = 0 while k: while i <= n and j < len(keep) and keep[j] == i: i += 1 j += 1 if k == 1: print(i) else: print(i, end=' ') k -= 1 i += 1 def solve(): global n global m global upper global lower for _ in range(m): u,v = map(int,input().split()) graph[u].append(v) graph[v].append(u) deg[u] += 1 deg[v] += 1 for i in range(1,n+1): mod[deg[i]%3].append(i) if n == 1: print("No") elif len(mod[0]) > 0: x = mod[0][0] print("Yes") print(n-1) for i in range(1,n): v = i + 1 if i >= x else i if i + 1 == n: print(v) else: print(v,end=' ') elif not forest(): keep.append(upper) keep.append(lower) #guardar todos los vértices del ciclo i = parent[lower] x = 0 y = 0 print('aqui') while i != upper: keep.append(i) y = depth[i] for v in graph[i]: if y > depth[v] and depth[v] >= depth[upper]: x = v y = depth[v] i = x answer() elif len(mod[1]) == 0: print("No") elif len(mod[1]) >= 2: pred[mod[1][0]] = -1 #cola queue q[0] = mod[1][0] i = 0 j = 1 k = q[0] while i < j: if i and deg[k] % 3 == 1: t = k break for v in graph[k]: if pred[v] == 0: pred[v] = k q[j] = v j += 1 i += 1 k = q[i] #guardar los vértices del camino i = t while ~i: keep.append(i) i = pred[i] answer() else: keep.append(mod[1][0]) fst = graph[mod[1][0]][0] pred[fst] = -1 q[0] = fst last = 0 i = 0 j = 1 k = q[0] while i < j: for v in graph[k]: if pred[v] == 0: if v == mod[1][0]: last = last if (last or (not i) ) else k else: pred[v] = k q[j] = v j += 1 i += 1 k = q[i] #agregar los vértices del primer camino i = last while ~i: keep.append(i) i = pred[i] #encontrar el otro camino for v in graph[mod[1][0]]: if pred[v] == 0: fst = v break last = 0 pred[fst] = -1 q[0] = fst i = 0 j = 1 k = q[0] while i < j: for v in graph[k]: if pred[v] == 0: if v == mod[1][0]: last = last if (last or (not i)) else k else: pred[v] = k q[j] = v j += 1 i += 1 k = q[i] i = last while ~i: keep.append(i) i = pred[i] answer() T = int(input()) for i in range(T): upper = 0 lower = 0 n, m = map(int,input().split()) graph = [[] for _ in range(n + 1)] deg = [0 for _ in range(n + 1)] q = [0 for _ in range(n + 1)] pred = [0 for _ in range(n + 1)] depth = [0 for _ in range(n + 1)] parent = [0 for _ in range(n + 1)] keep = [] mod = [[] for _ in range(3)] solve() if i != T - 1: _ = input() ```
instruction
0
104,520
13
209,040
No
output
1
104,520
13
209,041
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. I'm the Map, I'm the Map! I'm the MAP!!! Map In anticipation of new adventures Boots wanted to do a good deed. After discussion with the Map and Backpack, they decided to gift Dora a connected graph. After a long search, Boots chose t graph's variants, which Dora might like. However fox Swiper wants to spoil his plan. The Swiper knows, that Dora now is only able to count up to 3, so he has came up with a following idea. He wants to steal some non-empty set of vertices, so that the Dora won't notice the loss. He has decided to steal some non-empty set of vertices, so that after deletion of the stolen vertices and edges adjacent to them, every remaining vertex wouldn't change it's degree modulo 3. The degree of a vertex is the number of edges it is adjacent to. It would've been suspicious to steal all the vertices, so Swiper needs another plan. Boots are sure, that the crime can not be allowed. However they are afraid, that they won't be able to handle this alone. So Boots decided to ask for your help. Please determine for every graph's variant whether the Swiper can perform the theft or not. Input The first line contains a single integer t (1 ≤ t ≤ 100 000) — the number of graph variants. The first line of each variant contains integers n, m (1 ≤ n ≤ 500 000, 0 ≤ m ≤ 500 000), the number of vertexes and edges in the graph. Then m lines follow, each containing integers a_i, b_i (1 ≤ a_i, b_i ≤ n), the indices of the vertices connected with a corresponding edge. It's guaranteed, that the graph is connected and doesn't contain multiple edges or self-loops. It's guaranteed, that the sum of n over all variants is at most 500 000 and that the sum of m over all variants is at most 500 000. Descriptions of graph's variants are separated with an empty line. Output For each variant: * In case the answer exists, print "Yes" and then the answer itself. The first line should contain an integer c (1 < c < n), the number of vertices the Crook can steal, without Dora noticing the loss. On the next line print c distinct integers, the indices of the graph's vertices in arbitrary order. * Otherwise print "No". In case there are several correct ways to steal the vertices, print any of them. Please note, that it's not required to maximize the number of stolen vertices. Example Input 3 3 3 1 2 2 3 3 1 6 6 1 2 1 3 2 3 2 5 2 6 2 4 8 12 1 2 1 3 2 3 1 4 4 5 5 1 3 6 3 7 3 8 6 1 7 1 8 1 Output No Yes 3 4 5 6 Yes 3 6 7 8 Note The picture below shows the third variant from the example test. The set of the vertices the Crook can steal is denoted with bold. <image> Submitted Solution: ``` from typing import List import sys t_p = [] def get_ints(): return map(int, sys.stdin.readline().strip().split()) def puts(string: str): t_p.append(string) def print_solution(solution): for i in solution: can_pick[i] = False to_sol: List[str] = [] for i in range(1, n + 1): if can_pick[i]: to_sol.append(str(i)) if len(to_sol) == 0: puts('No') return puts('Yes') puts(str(len(to_sol))) puts(' '.join(to_sol)) path = [] def nodes_1_22(i): qi: List[int] = [0] * (n + 1) stack = [] stack.append(i) one_time = False while len(stack) > 0: u = stack[-1] if u != i: visited[u] = True else: visited[u] = False if qi[u] >= len(adj[u]): stack.pop() continue v = adj[u][qi[u]] qi[u] += 1 if parent[u] != v: if not visited[v]: if v != i: parent[v] = u stack.append(v) else: visited[v] = True x = u while parent[x] != 0: a = parent[x] if x == i: parent[x] = 0 path.append(x) x = a path.append(x) if one_time: print_solution(path) else: one_time = True def nodes_2(): path = [] qi: List[int] = [0] * (n + 1) stack = [] stack.append(1) while len(stack) > 0: u = stack[-1] visited[u] = True if qi[u] >= len(adj[u]): stack.pop() continue v = adj[u][qi[u]] qi[u] += 1 if parent[u] != v: if not visited[v]: parent[v] = u stack.append(v) else: x = v path.append(x) x = u while x != v: path.append(x) x = parent[x] path.append(x) print_solution(path) return def nodes_1(i): path = [] qi: List[int] = [0] * (n + 1) stack = [] stack.append(i) while len(stack) > 0: u = stack[-1] visited[u] = True if qi[u] == 0: for v in adj[u]: if v != i and len(adj[v]) % 3 == 1: x = u path.append(v) while parent[x] != 0: path.append(x) x = parent[x] path.append(x) print_solution(path) return if qi[u] >= len(adj[u]): stack.pop() continue v = adj[u][qi[u]] qi[u] += 1 if parent[u] != v: if not visited[v]: parent[v] = u if len(adj[v]) % 3 == 1: x = v while parent[x] != 0: path.append(x) x = parent[x] path.append(x) print_solution(path) return stack.append(v) def nodes_0(i): print_solution([i]) def solve(): node_1 = -1 for i in range(1, n + 1): if len(adj[i]) % 3 == 0: nodes_0(i) return for i in range(1, n + 1): if len(adj[i]) % 3 == 1: if node_1 != -1: nodes_1(node_1) return else: node_1 = i if node_1 == -1: nodes_2() else: nodes_1_22(node_1) if __name__ == '__main__': q = int(input()) # input() for qi in range(q): n, m = [int(a) for a in input().split(' ')] adj: List[List[int]] = [[]] + [[] for _ in range(n)] can_pick: List[bool] = [False] + ([True] * n) parent: List[int] = [0] * (n + 1) visited: List[bool] = [False] * (n + 1) for mi in range(m): # input() u, v = [int(a) for a in input().split(' ')] adj[u].append(v) adj[v].append(u) solve() if qi != q - 1: input() sys.stdout.write('\n'.join(t_p)) ```
instruction
0
104,521
13
209,042
No
output
1
104,521
13
209,043
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. I'm the Map, I'm the Map! I'm the MAP!!! Map In anticipation of new adventures Boots wanted to do a good deed. After discussion with the Map and Backpack, they decided to gift Dora a connected graph. After a long search, Boots chose t graph's variants, which Dora might like. However fox Swiper wants to spoil his plan. The Swiper knows, that Dora now is only able to count up to 3, so he has came up with a following idea. He wants to steal some non-empty set of vertices, so that the Dora won't notice the loss. He has decided to steal some non-empty set of vertices, so that after deletion of the stolen vertices and edges adjacent to them, every remaining vertex wouldn't change it's degree modulo 3. The degree of a vertex is the number of edges it is adjacent to. It would've been suspicious to steal all the vertices, so Swiper needs another plan. Boots are sure, that the crime can not be allowed. However they are afraid, that they won't be able to handle this alone. So Boots decided to ask for your help. Please determine for every graph's variant whether the Swiper can perform the theft or not. Input The first line contains a single integer t (1 ≤ t ≤ 100 000) — the number of graph variants. The first line of each variant contains integers n, m (1 ≤ n ≤ 500 000, 0 ≤ m ≤ 500 000), the number of vertexes and edges in the graph. Then m lines follow, each containing integers a_i, b_i (1 ≤ a_i, b_i ≤ n), the indices of the vertices connected with a corresponding edge. It's guaranteed, that the graph is connected and doesn't contain multiple edges or self-loops. It's guaranteed, that the sum of n over all variants is at most 500 000 and that the sum of m over all variants is at most 500 000. Descriptions of graph's variants are separated with an empty line. Output For each variant: * In case the answer exists, print "Yes" and then the answer itself. The first line should contain an integer c (1 < c < n), the number of vertices the Crook can steal, without Dora noticing the loss. On the next line print c distinct integers, the indices of the graph's vertices in arbitrary order. * Otherwise print "No". In case there are several correct ways to steal the vertices, print any of them. Please note, that it's not required to maximize the number of stolen vertices. Example Input 3 3 3 1 2 2 3 3 1 6 6 1 2 1 3 2 3 2 5 2 6 2 4 8 12 1 2 1 3 2 3 1 4 4 5 5 1 3 6 3 7 3 8 6 1 7 1 8 1 Output No Yes 3 4 5 6 Yes 3 6 7 8 Note The picture below shows the third variant from the example test. The set of the vertices the Crook can steal is denoted with bold. <image> Submitted Solution: ``` from typing import List import sys t_p = [] def get_ints(): return map(int, sys.stdin.readline().strip().split()) def puts(string: str): t_p.append(string) def print_solution(solution): for i in solution: can_pick[i] = False to_sol: List[str] = [] for i in range(1, n + 1): if can_pick[i]: to_sol.append(str(i)) if len(to_sol) == 0: puts('No') return puts('Yes') puts(str(len(to_sol))) puts(' '.join(to_sol)) path = [] def nodes_1_22(i): qi: List[int] = [0] * (n + 1) stack = [] stack.append(i) one_time = False while len(stack) > 0: u = stack[-1] if u != i: visited[u] = True else: visited[u] = False if qi[u] >= len(adj[u]): stack.pop() continue v = adj[u][qi[u]] qi[u] += 1 if parent[u] != v: if not visited[v]: if v != i: parent[v] = u stack.append(v) else: visited[v] = True x = u while parent[x] != 0: a = parent[x] if x == i: parent[x] = 0 path.append(x) x = a path.append(x) if one_time: print_solution(path) else: one_time = True def nodes_2(): path = [] qi: List[int] = [0] * (n + 1) stack = [] stack.append(1) while len(stack) > 0: u = stack[-1] visited[u] = True if qi[u] >= len(adj[u]): stack.pop() continue v = adj[u][qi[u]] qi[u] += 1 if parent[u] != v: if not visited[v]: parent[v] = u stack.append(v) else: x = v path.append(x) x = u while x != v: path.append(x) x = parent[x] path.append(x) print_solution(path) return def nodes_1(i): path = [] qi: List[int] = [0] * (n + 1) stack = [] stack.append(i) while len(stack) > 0: u = stack[-1] visited[u] = True if qi[u] == 0: for v in adj[u]: if v != i and len(adj[v]) % 3 == 1: x = u path.append(v) while parent[x] != 0: path.append(x) x = parent[x] path.append(x) print_solution(path) return if qi[u] >= len(adj[u]): stack.pop() continue v = adj[u][qi[u]] qi[u] += 1 if parent[u] != v: if not visited[v]: parent[v] = u if len(adj[v]) % 3 == 1: x = v while parent[x] != 0: path.append(x) x = parent[x] path.append(x) print_solution(path) return stack.append(v) def nodes_0(i): print_solution([i]) def solve(): node_1 = -1 for i in range(1, n + 1): if len(adj[i]) % 3 == 0: nodes_0(i) return for i in range(1, n + 1): if len(adj[i]) % 3 == 1: if node_1 != -1: nodes_1(node_1) return else: node_1 = i if node_1 == -1: nodes_2() else: nodes_1_22(node_1) if __name__ == '__main__': q = int(input()) # input() i = 0 while i < q: n, m = [int(a) for a in input().split(' ')] if q > 30000 and 159 < i < 160: print(n, m, sep=' ') adj: List[List[int]] = [[]] + [[] for _ in range(n)] can_pick: List[bool] = [False] + ([True] * n) parent: List[int] = [0] * (n + 1) visited: List[bool] = [False] * (n + 1) for mi in range(m): # input() u, v = [int(a) for a in input().split(' ')] adj[u].append(v) adj[v].append(u) if q > 30000 and 159 < i < 160: print(u, v, sep=' ') if q > 30000 and 159 < i < 160: print() if q < 30000: solve() if i != q - 1: input() i += 1 sys.stdout.write('\n'.join(t_p)) ```
instruction
0
104,522
13
209,044
No
output
1
104,522
13
209,045