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. Given is a rooted tree with N vertices numbered 1 to N. The root is Vertex 1, and the i-th edge (1 \leq i \leq N - 1) connects Vertex a_i and b_i. Each of the vertices has a counter installed. Initially, the counters on all the vertices have the value 0. Now, the following Q operations will be performed: * Operation j (1 \leq j \leq Q): Increment by x_j the counter on every vertex contained in the subtree rooted at Vertex p_j. Find the value of the counter on each vertex after all operations. Constraints * 2 \leq N \leq 2 \times 10^5 * 1 \leq Q \leq 2 \times 10^5 * 1 \leq a_i < b_i \leq N * 1 \leq p_j \leq N * 1 \leq x_j \leq 10^4 * The given graph is a tree. * All values in input are integers. Input Input is given from Standard Input in the following format: N Q a_1 b_1 : a_{N-1} b_{N-1} p_1 x_1 : p_Q x_Q Output Print the values of the counters on Vertex 1, 2, \ldots, N after all operations, in this order, with spaces in between. Examples Input 4 3 1 2 2 3 2 4 2 10 1 100 3 1 Output 100 110 111 110 Input 6 2 1 2 1 3 2 4 3 6 2 5 1 10 1 10 Output 20 20 20 20 20 20 Submitted Solution: ``` import sys input=sys.stdin.readline #from collections import defaultdict #d = defaultdict(int) #import fractions #import math #import collections #from collections import deque #from bisect import bisect_left #from bisect import insort_left #N = int(input()) #A = list(map(int,input().split())) #S = list(input()) #S.remove("\n") #N,M = map(int,input().split()) #S,T = map(str,input().split()) #A = [int(input()) for _ in range(N)] #S = [input() for _ in range(N)] #A = [list(map(int,input().split())) for _ in range(N)] #import itertools #import heapq #import numpy as np N,Q = map(int,input().split()) tree = [[] for _ in range(N)] cnt = [0]*N for _ in range(N-1): a,b = map(int,input().split()) tree[a-1].append(b-1) tree[b-1].append(a-1) for _ in range(Q): p,x = map(int,input().split()) cnt[p-1] += x sys.setrecursionlimit(10 ** 6) def dfs(cur,parent): li = tree[cur] for chi in li: if chi == parent: continue cnt[chi] += cnt[cur] dfs(chi,cur) dfs(0,-1) print(" ".join(map(str,cnt))) ```
instruction
0
31,589
13
63,178
No
output
1
31,589
13
63,179
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Mitya and Vasya are playing an interesting game. They have a rooted tree with n vertices, and the vertices are indexed from 1 to n. The root has index 1. Every other vertex i ≥ 2 has its parent p_i, and vertex i is called a child of vertex p_i. There are some cookies in every vertex of the tree: there are x_i cookies in vertex i. It takes exactly t_i time for Mitya to eat one cookie in vertex i. There is also a chip, which is initially located in the root of the tree, and it takes l_i time to move the chip along the edge connecting vertex i with its parent. Mitya and Vasya take turns playing, Mitya goes first. * Mitya moves the chip from the vertex, where the chip is located, to one of its children. * Vasya can remove an edge from the vertex, where the chip is located, to one of its children. Vasya can also decide to skip his turn. <image> Mitya can stop the game at any his turn. Once he stops the game, he moves the chip up to the root, eating some cookies along his way. Mitya can decide how many cookies he would like to eat in every vertex on his way. The total time spent on descend, ascend and eating cookies should not exceed T. Please note that in the end of the game the chip is always located in the root of the tree: Mitya can not leave the chip in any other vertex, even if he has already eaten enough cookies — he must move the chip back to the root (and every move from vertex v to its parent takes l_v time). Find out what is the maximum number of cookies Mitya can eat, regardless of Vasya's actions. Input The first line contains two integers n and T — the number of vertices in the tree and the time he has to accomplish his task (2≤ n ≤ 10^5; 1≤ T≤10^{18}). The second line contains n integers x_1, x_2, ..., x_n — number of cookies located in the corresponding vertex (1≤ x_i≤10^6). The third line contains n integers t_1, t_2, ..., t_n — how much time it takes Mitya to eat one cookie in vertex i (1≤ t_i≤10^6). Each of the following n - 1 lines describe the tree. For every i from 2 to n, the corresponding line contains two integers p_i and l_i, where p_i denotes the parent of vertex i and l_i denotes the time it takes Mitya to move the chip along the edge from vertex i to its parent (1≤ p_i < i, 0≤ l_i ≤ 10^9). Output Output a single integer — maximum number of cookies Mitya can eat. Examples Input 5 26 1 5 1 7 7 1 3 2 2 2 1 1 1 1 2 0 2 0 Output 11 Input 3 179 2 2 1 6 6 6 1 3 2 3 Output 4 Note In the first example test case, Mitya can start by moving the chip to vertex 2. In this case no matter how Vasya plays, Mitya is able to eat at least 11 cookies. Below you can find the detailed description of the moves: 1. Mitya moves chip to vertex 2. 2. Vasya removes edge to vertex 4. 3. Mitya moves chip to vertex 5. 4. Since vertex 5 has no children, Vasya does not remove any edges. 5. Mitya stops the game and moves the chip towards the root, eating cookies along the way (7 in vertex 5, 3 in vertex 2, 1 in vertex 1). Mitya spend 1+0 time to go down, 0+1 to go up, 7⋅ 2 to eat 7 cookies in vertex 5, 3⋅ 3 to eat 3 cookies in vertex 2, 1⋅ 1 to eat 1 cookie in vertex 1. Total time is 1+0+0+1+7⋅ 2+3⋅ 3+1⋅ 1=26. Submitted Solution: ``` import math import sys n,T = map(int,input().split()) cookies = list(map(int,input().split())) time = list(map(int,input().split())) dict1 = {} dictpl = {} for i in range(2,n+1): p,l = map(int,input().split()) if p in dict1: dict1[p].append(i) else: dict1[p] = [i] dictpl[i] = (p,l) cookie = {} cookietime = {} cookie[1] = (min(cookies[0],math.floor(T/time[0])),min(T,time[0]*cookies[0])) cookietime[1] = [(time[0],min(cookies[0],math.floor(T/time[0])))] def countCookie(ind): if ind in cookie: return cookie[ind] else: p,l = dictpl[ind] if p not in cookie: cookie[p] = countCookie(p) cookietime[ind] = [] for t in cookietime[p]: cookietime[ind].append(t) thisc = cookies[ind-1] thist = time[ind-1] cookietime[ind].append((thist,thisc)) cookietime[ind].sort() parentc = cookie[p][0] parentt = cookie[p][1] totalcookie = thisc + parentc totaltime = parentt + thisc*thist+ 2* l while totaltime > T: lastt,lastc = cookietime[ind].pop() canremove = min(lastc, math.ceil((totaltime-T)/lastt)) totaltime -= canremove*lastt totalcookie -= canremove if canremove < lastc: cookietime[ind].append((lastt, lastc - canremove)) cookie[ind] = (totalcookie, totaltime) return cookie[ind] for i in range(2,n+1): countCookie(i) def getMost(i): if i in dict1: l = [] for j in dict1[i]: l.append(getMost(j)) l.sort() if len(l)>=2: return l[-2] else: return cookie[i][0] else: return cookie[i][0] m = cookie[1][0] for i in dict1[1]: m = max(m,getMost(i)) print(m) ```
instruction
0
31,807
13
63,614
No
output
1
31,807
13
63,615
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Mitya and Vasya are playing an interesting game. They have a rooted tree with n vertices, and the vertices are indexed from 1 to n. The root has index 1. Every other vertex i ≥ 2 has its parent p_i, and vertex i is called a child of vertex p_i. There are some cookies in every vertex of the tree: there are x_i cookies in vertex i. It takes exactly t_i time for Mitya to eat one cookie in vertex i. There is also a chip, which is initially located in the root of the tree, and it takes l_i time to move the chip along the edge connecting vertex i with its parent. Mitya and Vasya take turns playing, Mitya goes first. * Mitya moves the chip from the vertex, where the chip is located, to one of its children. * Vasya can remove an edge from the vertex, where the chip is located, to one of its children. Vasya can also decide to skip his turn. <image> Mitya can stop the game at any his turn. Once he stops the game, he moves the chip up to the root, eating some cookies along his way. Mitya can decide how many cookies he would like to eat in every vertex on his way. The total time spent on descend, ascend and eating cookies should not exceed T. Please note that in the end of the game the chip is always located in the root of the tree: Mitya can not leave the chip in any other vertex, even if he has already eaten enough cookies — he must move the chip back to the root (and every move from vertex v to its parent takes l_v time). Find out what is the maximum number of cookies Mitya can eat, regardless of Vasya's actions. Input The first line contains two integers n and T — the number of vertices in the tree and the time he has to accomplish his task (2≤ n ≤ 10^5; 1≤ T≤10^{18}). The second line contains n integers x_1, x_2, ..., x_n — number of cookies located in the corresponding vertex (1≤ x_i≤10^6). The third line contains n integers t_1, t_2, ..., t_n — how much time it takes Mitya to eat one cookie in vertex i (1≤ t_i≤10^6). Each of the following n - 1 lines describe the tree. For every i from 2 to n, the corresponding line contains two integers p_i and l_i, where p_i denotes the parent of vertex i and l_i denotes the time it takes Mitya to move the chip along the edge from vertex i to its parent (1≤ p_i < i, 0≤ l_i ≤ 10^9). Output Output a single integer — maximum number of cookies Mitya can eat. Examples Input 5 26 1 5 1 7 7 1 3 2 2 2 1 1 1 1 2 0 2 0 Output 11 Input 3 179 2 2 1 6 6 6 1 3 2 3 Output 4 Note In the first example test case, Mitya can start by moving the chip to vertex 2. In this case no matter how Vasya plays, Mitya is able to eat at least 11 cookies. Below you can find the detailed description of the moves: 1. Mitya moves chip to vertex 2. 2. Vasya removes edge to vertex 4. 3. Mitya moves chip to vertex 5. 4. Since vertex 5 has no children, Vasya does not remove any edges. 5. Mitya stops the game and moves the chip towards the root, eating cookies along the way (7 in vertex 5, 3 in vertex 2, 1 in vertex 1). Mitya spend 1+0 time to go down, 0+1 to go up, 7⋅ 2 to eat 7 cookies in vertex 5, 3⋅ 3 to eat 3 cookies in vertex 2, 1⋅ 1 to eat 1 cookie in vertex 1. Total time is 1+0+0+1+7⋅ 2+3⋅ 3+1⋅ 1=26. Submitted Solution: ``` import math import sys n,T = map(int,input().split()) cookies = list(map(int,input().split())) time = list(map(int,input().split())) dict1 = {} dictpl = {} for i in range(2,n+1): p,l = map(int,input().split()) if p in dict1: dict1[p].append(i) else: dict1[p] = [i] dictpl[i] = (p,l) cookie = {} cookietime = {} cookie[1] = (min(cookies[0],math.floor(T/time[0])),min(T,time[0]*cookies[0])) cookietime[1] = [(time[0],min(cookies[0],math.floor(T/time[0])))] def countCookie(ind): if ind in cookie: return cookie[ind] else: p,l = dictpl[ind] if p not in cookie: cookie[p] = countCookie(p) cookietime[ind] = cookietime[p] thisc = cookies[ind-1] thist = time[ind-1] cookietime[ind].append((thist,thisc)) cookietime[ind].sort() parentc = cookie[p][0] parentt = cookie[p][1] totalcookie = thisc + parentc totaltime = parentt + thisc*thist+ 2* l while totaltime > T: lastt,lastc = cookietime[ind].pop() canremove = min(lastc, math.ceil((totaltime-T)/lastt)) totaltime -= canremove*lastt totalcookie -= canremove if canremove < lastc: cookietime[ind].append((lastt, lastc - canremove)) cookie[ind] = (totalcookie, totaltime) return cookie[ind] for i in range(2,n+1): countCookie(i) def getMost(i): if i in dict1: l = [] for j in dict1[i]: l.append(getMost(j)) l.sort() if len(l)>=2: return l[-2] else: return cookie[i][0] else: return cookie[i][0] m = -1 for i in dict1[1]: m = max(m,getMost(i)) print(m) ```
instruction
0
31,808
13
63,616
No
output
1
31,808
13
63,617
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Mitya and Vasya are playing an interesting game. They have a rooted tree with n vertices, and the vertices are indexed from 1 to n. The root has index 1. Every other vertex i ≥ 2 has its parent p_i, and vertex i is called a child of vertex p_i. There are some cookies in every vertex of the tree: there are x_i cookies in vertex i. It takes exactly t_i time for Mitya to eat one cookie in vertex i. There is also a chip, which is initially located in the root of the tree, and it takes l_i time to move the chip along the edge connecting vertex i with its parent. Mitya and Vasya take turns playing, Mitya goes first. * Mitya moves the chip from the vertex, where the chip is located, to one of its children. * Vasya can remove an edge from the vertex, where the chip is located, to one of its children. Vasya can also decide to skip his turn. <image> Mitya can stop the game at any his turn. Once he stops the game, he moves the chip up to the root, eating some cookies along his way. Mitya can decide how many cookies he would like to eat in every vertex on his way. The total time spent on descend, ascend and eating cookies should not exceed T. Please note that in the end of the game the chip is always located in the root of the tree: Mitya can not leave the chip in any other vertex, even if he has already eaten enough cookies — he must move the chip back to the root (and every move from vertex v to its parent takes l_v time). Find out what is the maximum number of cookies Mitya can eat, regardless of Vasya's actions. Input The first line contains two integers n and T — the number of vertices in the tree and the time he has to accomplish his task (2≤ n ≤ 10^5; 1≤ T≤10^{18}). The second line contains n integers x_1, x_2, ..., x_n — number of cookies located in the corresponding vertex (1≤ x_i≤10^6). The third line contains n integers t_1, t_2, ..., t_n — how much time it takes Mitya to eat one cookie in vertex i (1≤ t_i≤10^6). Each of the following n - 1 lines describe the tree. For every i from 2 to n, the corresponding line contains two integers p_i and l_i, where p_i denotes the parent of vertex i and l_i denotes the time it takes Mitya to move the chip along the edge from vertex i to its parent (1≤ p_i < i, 0≤ l_i ≤ 10^9). Output Output a single integer — maximum number of cookies Mitya can eat. Examples Input 5 26 1 5 1 7 7 1 3 2 2 2 1 1 1 1 2 0 2 0 Output 11 Input 3 179 2 2 1 6 6 6 1 3 2 3 Output 4 Note In the first example test case, Mitya can start by moving the chip to vertex 2. In this case no matter how Vasya plays, Mitya is able to eat at least 11 cookies. Below you can find the detailed description of the moves: 1. Mitya moves chip to vertex 2. 2. Vasya removes edge to vertex 4. 3. Mitya moves chip to vertex 5. 4. Since vertex 5 has no children, Vasya does not remove any edges. 5. Mitya stops the game and moves the chip towards the root, eating cookies along the way (7 in vertex 5, 3 in vertex 2, 1 in vertex 1). Mitya spend 1+0 time to go down, 0+1 to go up, 7⋅ 2 to eat 7 cookies in vertex 5, 3⋅ 3 to eat 3 cookies in vertex 2, 1⋅ 1 to eat 1 cookie in vertex 1. Total time is 1+0+0+1+7⋅ 2+3⋅ 3+1⋅ 1=26. Submitted Solution: ``` import math import sys n,T = map(int,input().split()) cookies = list(map(int,input().split())) time = list(map(int,input().split())) dict1 = {} dictpl = {} for i in range(2,n+1): p,l = map(int,input().split()) if p in dict1: dict1[p].append(i) else: dict1[p] = [i] dictpl[i] = (p,l) cookie = {} cookietime = {} cookie[1] = (min(cookies[0],math.floor(T/time[0])),min(T,time[0]*cookies[0])) cookietime[1] = [(time[0],min(cookies[0],math.floor(T/time[0])))] def countCookie(ind): if ind in cookie: return cookie[ind] else: p,l = dictpl[ind] if p not in cookie: cookie[p] = countCookie(p) cookietime[ind] = cookietime[p] thisc = cookies[ind-1] thist = time[ind-1] cookietime[ind].append((thist,thisc)) cookietime[ind].sort() parentc = cookie[p][0] parentt = cookie[p][1] totalcookie = thisc + parentc totaltime = parentt + thisc*thist+ 2* l while totaltime > T: lastt,lastc = cookietime[ind].pop() canremove = min(lastc, math.ceil((totaltime-T)/lastt)) totaltime -= canremove*lastt totalcookie -= canremove if canremove < lastc: cookietime[ind].append((lastt, lastc - canremove)) cookie[ind] = (totalcookie, totaltime) return cookie[ind] for i in range(2,n+1): countCookie(i) def getMost(i): if i in dict1: l = [] for j in dict1[i]: l.append(getMost(j)) l.sort() if len(l)>=2: return l[-2] else: return cookie[i][0] else: return cookie[i][0] m = cookie[1][0] for i in dict1[1]: m = max(m,getMost(i)) print(m) ```
instruction
0
31,809
13
63,618
No
output
1
31,809
13
63,619
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vus the Cossack has a simple graph with n vertices and m edges. Let d_i be a degree of the i-th vertex. Recall that a degree of the i-th vertex is the number of conected edges to the i-th vertex. He needs to remain not more than ⌈ (n+m)/(2) ⌉ edges. Let f_i be the degree of the i-th vertex after removing. He needs to delete them in such way so that ⌈ (d_i)/(2) ⌉ ≤ f_i for each i. In other words, the degree of each vertex should not be reduced more than twice. Help Vus to remain the needed edges! Input The first line contains two integers n and m (1 ≤ n ≤ 10^6, 0 ≤ m ≤ 10^6) — the number of vertices and edges respectively. Each of the next m lines contains two integers u_i and v_i (1 ≤ u_i, v_i ≤ n) — vertices between which there is an edge. It is guaranteed that the graph does not have loops and multiple edges. It is possible to show that the answer always exists. Output In the first line, print one integer k (0 ≤ k ≤ ⌈ (n+m)/(2) ⌉) — the number of edges which you need to remain. In each of the next k lines, print two integers u_i and v_i (1 ≤ u_i, v_i ≤ n) — the vertices, the edge between which, you need to remain. You can not print the same edge more than once. Examples Input 6 6 1 2 2 3 3 4 4 5 5 3 6 5 Output 5 2 1 3 2 5 3 5 4 6 5 Input 10 20 4 3 6 5 4 5 10 8 4 8 5 8 10 4 9 5 5 1 3 8 1 2 4 7 1 4 10 7 1 7 6 1 9 6 3 9 7 9 6 2 Output 12 2 1 4 1 5 4 6 5 7 1 7 4 8 3 8 5 9 3 9 6 10 4 10 7 Submitted Solution: ``` from random import shuffle n, m = map(int, input().split()) R = [] for i in range(m): R.append(list(map(int, input().split()))) shuffle(R) R = R[:(n + m + 1)//2] print((n + m + 1)//2) for u, v in R: print(u, v) ##### ```
instruction
0
31,842
13
63,684
No
output
1
31,842
13
63,685
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vus the Cossack has a simple graph with n vertices and m edges. Let d_i be a degree of the i-th vertex. Recall that a degree of the i-th vertex is the number of conected edges to the i-th vertex. He needs to remain not more than ⌈ (n+m)/(2) ⌉ edges. Let f_i be the degree of the i-th vertex after removing. He needs to delete them in such way so that ⌈ (d_i)/(2) ⌉ ≤ f_i for each i. In other words, the degree of each vertex should not be reduced more than twice. Help Vus to remain the needed edges! Input The first line contains two integers n and m (1 ≤ n ≤ 10^6, 0 ≤ m ≤ 10^6) — the number of vertices and edges respectively. Each of the next m lines contains two integers u_i and v_i (1 ≤ u_i, v_i ≤ n) — vertices between which there is an edge. It is guaranteed that the graph does not have loops and multiple edges. It is possible to show that the answer always exists. Output In the first line, print one integer k (0 ≤ k ≤ ⌈ (n+m)/(2) ⌉) — the number of edges which you need to remain. In each of the next k lines, print two integers u_i and v_i (1 ≤ u_i, v_i ≤ n) — the vertices, the edge between which, you need to remain. You can not print the same edge more than once. Examples Input 6 6 1 2 2 3 3 4 4 5 5 3 6 5 Output 5 2 1 3 2 5 3 5 4 6 5 Input 10 20 4 3 6 5 4 5 10 8 4 8 5 8 10 4 9 5 5 1 3 8 1 2 4 7 1 4 10 7 1 7 6 1 9 6 3 9 7 9 6 2 Output 12 2 1 4 1 5 4 6 5 7 1 7 4 8 3 8 5 9 3 9 6 10 4 10 7 Submitted Solution: ``` from __future__ import print_function def euler(node): path = [] while deg[node]: path.append(node) while deg[node]: deg[node] -= 1 nxt_node = adj[node].pop() idx = edge_index[node].pop() if used_edge[idx] == False: used_edge[idx] = True node = nxt_node break return path def has_dummy(a, b): return a == 0 or b == 0 n, m = map(int, input().split()) print(n, m) in_idx = 0 n += 1 adj = [[] for _ in range(n)] edge_index = [[] for _ in range(n)] for i in range(m): a, b = map(int, input().split()) adj[a].append(b) edge_index[a].append(i) adj[b].append(a) edge_index[b].append(i) deg = [len(adj[node]) for node in range(n)] for x in range(n): if deg[x] & 1: adj[0].append(x) edge_index[0].append(m) deg[0] += 1 adj[x].append(0) edge_index[x].append(m) deg[x] += 1 m += 1 used_edge = [False] * m out = [] for node in range(n): path = euler(node) pre = False for i in range(1, len(path)): b = path[i] a = path[i - 1] removed = False if has_dummy(a, b): removed = True elif (i + 1 < len(path)) and path[i + 1] == 0: removed = False elif i & 1 == 0 and pre == False: removed = True if removed == False: out.append('%d %d' % (a, b)) pre = removed print(len(out)) print('\n'.join(out)) ```
instruction
0
31,843
13
63,686
No
output
1
31,843
13
63,687
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vus the Cossack has a simple graph with n vertices and m edges. Let d_i be a degree of the i-th vertex. Recall that a degree of the i-th vertex is the number of conected edges to the i-th vertex. He needs to remain not more than ⌈ (n+m)/(2) ⌉ edges. Let f_i be the degree of the i-th vertex after removing. He needs to delete them in such way so that ⌈ (d_i)/(2) ⌉ ≤ f_i for each i. In other words, the degree of each vertex should not be reduced more than twice. Help Vus to remain the needed edges! Input The first line contains two integers n and m (1 ≤ n ≤ 10^6, 0 ≤ m ≤ 10^6) — the number of vertices and edges respectively. Each of the next m lines contains two integers u_i and v_i (1 ≤ u_i, v_i ≤ n) — vertices between which there is an edge. It is guaranteed that the graph does not have loops and multiple edges. It is possible to show that the answer always exists. Output In the first line, print one integer k (0 ≤ k ≤ ⌈ (n+m)/(2) ⌉) — the number of edges which you need to remain. In each of the next k lines, print two integers u_i and v_i (1 ≤ u_i, v_i ≤ n) — the vertices, the edge between which, you need to remain. You can not print the same edge more than once. Examples Input 6 6 1 2 2 3 3 4 4 5 5 3 6 5 Output 5 2 1 3 2 5 3 5 4 6 5 Input 10 20 4 3 6 5 4 5 10 8 4 8 5 8 10 4 9 5 5 1 3 8 1 2 4 7 1 4 10 7 1 7 6 1 9 6 3 9 7 9 6 2 Output 12 2 1 4 1 5 4 6 5 7 1 7 4 8 3 8 5 9 3 9 6 10 4 10 7 Submitted Solution: ``` import sys from collections import deque IS_LOCAL = False def read_one(dtype=int): return dtype(input()) def read_multiple(f, dtype=int): return f(map(dtype, input().split())) def swap(x, y): return y, x def dfs(vs, n): visited, path, indices = [0]*n, [(0, 0)]*n, [0]*n stack = deque() stack.append((None, 0, None)) i = 0 while stack: u, v, ei = stack.pop() if visited[v] > 0: continue visited[v] = 1 for t, tei in vs[v]: if visited[t] == 0: stack.append((v, t, tei)) if u is not None: if u > v: t = u u = v v = t path[i] = (u, v) indices[i] = ei i += 1 return path, indices def main(): n, m = 5, 7 edges = [(1, 2), (2, 3), (3, 4), (4, 5), (5, 3), (1, 4), (5, 1)] vs = None ds, fs = None, None if not IS_LOCAL: n, m = read_multiple(tuple) edges = [(0, 0)] * m vs = [[] for _ in range(n)] ds = [0] * n for i in range(m): u, v = read_multiple(tuple) if u > v: t = u u = v v = t u, v = u-1, v-1 edges[i] = (u, v) vs[u].append((v, i)) vs[v].append((u, i)) ds[u] += 1 ds[v] += 1 result, visited_indices = dfs(vs, n) fs = ds.copy() for i in visited_indices: edges[i] = None for i in range(m): if edges[i] is None: continue u, v = edges[i] uhd = (ds[u] + 1) // 2 vhd = (ds[v] + 1) // 2 uf = fs[u] vf = fs[v] if uf > uhd and vf > vhd: fs[u] -= 1 fs[v] -= 1 else: result.append((u, v)) print(len(result)) print('\n'.join([f'{u+1} {v+1}' for u, v in result])) if __name__ == "__main__": if len(sys.argv) > 1 and sys.argv[1] == 'True': IS_LOCAL = True main() ```
instruction
0
31,844
13
63,688
No
output
1
31,844
13
63,689
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vus the Cossack has a simple graph with n vertices and m edges. Let d_i be a degree of the i-th vertex. Recall that a degree of the i-th vertex is the number of conected edges to the i-th vertex. He needs to remain not more than ⌈ (n+m)/(2) ⌉ edges. Let f_i be the degree of the i-th vertex after removing. He needs to delete them in such way so that ⌈ (d_i)/(2) ⌉ ≤ f_i for each i. In other words, the degree of each vertex should not be reduced more than twice. Help Vus to remain the needed edges! Input The first line contains two integers n and m (1 ≤ n ≤ 10^6, 0 ≤ m ≤ 10^6) — the number of vertices and edges respectively. Each of the next m lines contains two integers u_i and v_i (1 ≤ u_i, v_i ≤ n) — vertices between which there is an edge. It is guaranteed that the graph does not have loops and multiple edges. It is possible to show that the answer always exists. Output In the first line, print one integer k (0 ≤ k ≤ ⌈ (n+m)/(2) ⌉) — the number of edges which you need to remain. In each of the next k lines, print two integers u_i and v_i (1 ≤ u_i, v_i ≤ n) — the vertices, the edge between which, you need to remain. You can not print the same edge more than once. Examples Input 6 6 1 2 2 3 3 4 4 5 5 3 6 5 Output 5 2 1 3 2 5 3 5 4 6 5 Input 10 20 4 3 6 5 4 5 10 8 4 8 5 8 10 4 9 5 5 1 3 8 1 2 4 7 1 4 10 7 1 7 6 1 9 6 3 9 7 9 6 2 Output 12 2 1 4 1 5 4 6 5 7 1 7 4 8 3 8 5 9 3 9 6 10 4 10 7 Submitted Solution: ``` import sys from collections import deque IS_LOCAL = False def read_one(dtype=int): return dtype(input()) def read_multiple(f, dtype=int): return f(map(dtype, input().split())) def swap(x, y): return y, x def dfs(vs, n): visited, path, indices = [0]*n, [], [] stack = deque() stack.append((None, 0, None)) i = 0 while stack: u, v, ei = stack.pop() if visited[v] > 0: continue visited[v] = 1 for t, tei in vs[v]: if visited[t] == 0: stack.append((v, t, tei)) if u is not None: if u > v: t = u u = v v = t # path[i] = (u, v) # indices[i] = ei path.append((u,v)) indices.append(ei) i += 1 if i == n-1: break return path, indices def main(): n, m = 5, 7 edges = [(1, 2), (2, 3), (3, 4), (4, 5), (5, 3), (1, 4), (5, 1)] vs = None ds, fs = None, None if not IS_LOCAL: n, m = read_multiple(tuple) edges = [(0, 0)] * m vs = [[] for _ in range(n)] ds = [0] * n for i in range(m): u, v = read_multiple(tuple) if u > v: t = u u = v v = t u, v = u-1, v-1 edges[i] = (u, v) # edges.append((u, v)) vs[u].append((v, i)) vs[v].append((u, i)) ds[u] += 1 ds[v] += 1 result, visited_indices = dfs(vs, n) edges_left = m - (n - 1) fs = [0]*n for i in range(n-1): edges[visited_indices[i]] = None u, v = result[i] fs[u] += 1 fs[v] += 1 bad_vs = 0 for u in range(n): if fs[u] < (ds[u] + 1) // 2: bad_vs += 1 if bad_vs > 0: for i in range(m): if edges[i] is None: continue u, v = edges[i] uhd = (ds[u] + 1) // 2 vhd = (ds[v] + 1) // 2 uf = fs[u] vf = fs[v] if uf < uhd and vf < vhd: fs[u] += 1 fs[v] += 1 result.append((u, v)) print(len(result)) print('\n'.join([f'{u+1} {v+1}' for u, v in result])) if __name__ == "__main__": if len(sys.argv) > 1 and sys.argv[1] == 'True': IS_LOCAL = True main() ```
instruction
0
31,845
13
63,690
No
output
1
31,845
13
63,691
Provide tags and a correct Python 3 solution for this coding contest problem. John Doe started thinking about graphs. After some thought he decided that he wants to paint an undirected graph, containing exactly k cycles of length 3. A cycle of length 3 is an unordered group of three distinct graph vertices a, b and c, such that each pair of them is connected by a graph edge. John has been painting for long, but he has not been a success. Help him find such graph. Note that the number of vertices there shouldn't exceed 100, or else John will have problems painting it. Input A single line contains an integer k (1 ≤ k ≤ 105) — the number of cycles of length 3 in the required graph. Output In the first line print integer n (3 ≤ n ≤ 100) — the number of vertices in the found graph. In each of next n lines print n characters "0" and "1": the i-th character of the j-th line should equal "0", if vertices i and j do not have an edge between them, otherwise it should equal "1". Note that as the required graph is undirected, the i-th character of the j-th line must equal the j-th character of the i-th line. The graph shouldn't contain self-loops, so the i-th character of the i-th line must equal "0" for all i. Examples Input 1 Output 3 011 101 110 Input 10 Output 5 01111 10111 11011 11101 11110
instruction
0
32,004
13
64,008
Tags: binary search, constructive algorithms, graphs, greedy Correct Solution: ``` n , k = 0 , int(input()) p=[['0']*100 for i in range(100)] while k: for i in range(n): if i>k: break p[n][i]=p[i][n]='1' k=k-i n+=1 print(n) for i in range(n): print(''.join(p[i][:n])) ```
output
1
32,004
13
64,009
Provide tags and a correct Python 3 solution for this coding contest problem. John Doe started thinking about graphs. After some thought he decided that he wants to paint an undirected graph, containing exactly k cycles of length 3. A cycle of length 3 is an unordered group of three distinct graph vertices a, b and c, such that each pair of them is connected by a graph edge. John has been painting for long, but he has not been a success. Help him find such graph. Note that the number of vertices there shouldn't exceed 100, or else John will have problems painting it. Input A single line contains an integer k (1 ≤ k ≤ 105) — the number of cycles of length 3 in the required graph. Output In the first line print integer n (3 ≤ n ≤ 100) — the number of vertices in the found graph. In each of next n lines print n characters "0" and "1": the i-th character of the j-th line should equal "0", if vertices i and j do not have an edge between them, otherwise it should equal "1". Note that as the required graph is undirected, the i-th character of the j-th line must equal the j-th character of the i-th line. The graph shouldn't contain self-loops, so the i-th character of the i-th line must equal "0" for all i. Examples Input 1 Output 3 011 101 110 Input 10 Output 5 01111 10111 11011 11101 11110
instruction
0
32,005
13
64,010
Tags: binary search, constructive algorithms, graphs, greedy Correct Solution: ``` # Author : nitish420 -------------------------------------------------------------------- import os import sys from io import BytesIO, IOBase def main(): k=int(input()) l=3 r=100 while l<=r : n=l+((r-l)>>1) if (n*(n-1)*(n-2))//6 <= k: l=n+1 else: r=n-1 n=l-1 ans=[[0 for _ in range(100)] for _ in range(100)] for i in range(n): for j in range(i+1,n): ans[i][j]=ans[j][i]=1 k-=(n*(n-1)*(n-2))//6 while k>0: z=2 while ((z+1)*z)>>1 <=k: z+=1 k-=((z*(z-1))>>1) n+=1 for i in range(z): ans[i][n]=ans[n][i]=1 print(100) for item in ans: print(*item,sep="") #---------------------------------------------------------------------------------------- # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = 'x' in file.mode or 'r' not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b'\n') + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode('ascii')) self.read = lambda: self.buffer.read().decode('ascii') self.readline = lambda: self.buffer.readline().decode('ascii') sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip('\r\n') # endregion if __name__ == '__main__': main() ```
output
1
32,005
13
64,011
Provide tags and a correct Python 3 solution for this coding contest problem. John Doe started thinking about graphs. After some thought he decided that he wants to paint an undirected graph, containing exactly k cycles of length 3. A cycle of length 3 is an unordered group of three distinct graph vertices a, b and c, such that each pair of them is connected by a graph edge. John has been painting for long, but he has not been a success. Help him find such graph. Note that the number of vertices there shouldn't exceed 100, or else John will have problems painting it. Input A single line contains an integer k (1 ≤ k ≤ 105) — the number of cycles of length 3 in the required graph. Output In the first line print integer n (3 ≤ n ≤ 100) — the number of vertices in the found graph. In each of next n lines print n characters "0" and "1": the i-th character of the j-th line should equal "0", if vertices i and j do not have an edge between them, otherwise it should equal "1". Note that as the required graph is undirected, the i-th character of the j-th line must equal the j-th character of the i-th line. The graph shouldn't contain self-loops, so the i-th character of the i-th line must equal "0" for all i. Examples Input 1 Output 3 011 101 110 Input 10 Output 5 01111 10111 11011 11101 11110
instruction
0
32,006
13
64,012
Tags: binary search, constructive algorithms, graphs, greedy Correct Solution: ``` import sys import math c=int(input()) Ans=[] F=[1] for i in range(1,101): F.append(F[-1]*i) for i in range(100): Ans.append([0]*100) print(100) cycles=1 Ans[0][1]=1 Ans[1][0]=1 Ans[1][2]=1 Ans[2][1]=1 Ans[0][2]=1 Ans[2][0]=1 m=3 while(cycles<c): Ans[0][m]=1 Ans[m][0]=1 inc=1 for j in range(1,m): Ans[j][m]=1 Ans[m][j]=1 cycles+=inc inc+=1 if(cycles+inc>c): break m+=1 A="" for i in range(100): for j in range(100): A+=str(Ans[i][j]) A+="\n" sys.stdout.write(A) ```
output
1
32,006
13
64,013
Provide tags and a correct Python 3 solution for this coding contest problem. John Doe started thinking about graphs. After some thought he decided that he wants to paint an undirected graph, containing exactly k cycles of length 3. A cycle of length 3 is an unordered group of three distinct graph vertices a, b and c, such that each pair of them is connected by a graph edge. John has been painting for long, but he has not been a success. Help him find such graph. Note that the number of vertices there shouldn't exceed 100, or else John will have problems painting it. Input A single line contains an integer k (1 ≤ k ≤ 105) — the number of cycles of length 3 in the required graph. Output In the first line print integer n (3 ≤ n ≤ 100) — the number of vertices in the found graph. In each of next n lines print n characters "0" and "1": the i-th character of the j-th line should equal "0", if vertices i and j do not have an edge between them, otherwise it should equal "1". Note that as the required graph is undirected, the i-th character of the j-th line must equal the j-th character of the i-th line. The graph shouldn't contain self-loops, so the i-th character of the i-th line must equal "0" for all i. Examples Input 1 Output 3 011 101 110 Input 10 Output 5 01111 10111 11011 11101 11110
instruction
0
32,007
13
64,014
Tags: binary search, constructive algorithms, graphs, greedy Correct Solution: ``` n = int( input() ) a = [] MAXN = 100 for i in range(MAXN): a.append( [0]*MAXN ) for i in range(3): for j in range(3): if i != j: a[i][j] = 1 cycles = 1 if cycles != n: for i in range(3,MAXN): if cycles == n: break a[i][0] = a[0][i] = 1 a[i][1] = a[1][i] = 1 cycles += 1 if cycles == n: break how = 2 for j in range(2,i): if j != i: if cycles + how <= n: a[i][j] = a[j][i] = 1 cycles += how how += 1 if cycles == n: break print(MAXN) for i in range( len(a) ): for j in a[i]: print( j, end='') print() ```
output
1
32,007
13
64,015
Provide tags and a correct Python 3 solution for this coding contest problem. John Doe started thinking about graphs. After some thought he decided that he wants to paint an undirected graph, containing exactly k cycles of length 3. A cycle of length 3 is an unordered group of three distinct graph vertices a, b and c, such that each pair of them is connected by a graph edge. John has been painting for long, but he has not been a success. Help him find such graph. Note that the number of vertices there shouldn't exceed 100, or else John will have problems painting it. Input A single line contains an integer k (1 ≤ k ≤ 105) — the number of cycles of length 3 in the required graph. Output In the first line print integer n (3 ≤ n ≤ 100) — the number of vertices in the found graph. In each of next n lines print n characters "0" and "1": the i-th character of the j-th line should equal "0", if vertices i and j do not have an edge between them, otherwise it should equal "1". Note that as the required graph is undirected, the i-th character of the j-th line must equal the j-th character of the i-th line. The graph shouldn't contain self-loops, so the i-th character of the i-th line must equal "0" for all i. Examples Input 1 Output 3 011 101 110 Input 10 Output 5 01111 10111 11011 11101 11110
instruction
0
32,008
13
64,016
Tags: binary search, constructive algorithms, graphs, greedy Correct Solution: ``` n, k = 0, int(input()) p = [['0'] * 100 for i in range(100)] while k: for i in range(n): if i > k: break p[n][i] = p[i][n] = '1' k -= i n += 1 print(n) for i in range(n): print(''.join(p[i][:n])) ```
output
1
32,008
13
64,017
Provide tags and a correct Python 3 solution for this coding contest problem. John Doe started thinking about graphs. After some thought he decided that he wants to paint an undirected graph, containing exactly k cycles of length 3. A cycle of length 3 is an unordered group of three distinct graph vertices a, b and c, such that each pair of them is connected by a graph edge. John has been painting for long, but he has not been a success. Help him find such graph. Note that the number of vertices there shouldn't exceed 100, or else John will have problems painting it. Input A single line contains an integer k (1 ≤ k ≤ 105) — the number of cycles of length 3 in the required graph. Output In the first line print integer n (3 ≤ n ≤ 100) — the number of vertices in the found graph. In each of next n lines print n characters "0" and "1": the i-th character of the j-th line should equal "0", if vertices i and j do not have an edge between them, otherwise it should equal "1". Note that as the required graph is undirected, the i-th character of the j-th line must equal the j-th character of the i-th line. The graph shouldn't contain self-loops, so the i-th character of the i-th line must equal "0" for all i. Examples Input 1 Output 3 011 101 110 Input 10 Output 5 01111 10111 11011 11101 11110
instruction
0
32,009
13
64,018
Tags: binary search, constructive algorithms, graphs, greedy Correct Solution: ``` k=int(input()) i=3 while (i-2)*(i-1)*i//6<k: i+=1 a=[[1 for j in range(i)] for k in range(i)] b=(i-2)*(i-1)*i//6 j=0 while b>k: b-=i-2 a[j*2][j*2+1]=0 a[j*2+1][j*2]=0 j+=1 while k-b>0: l=3 while (l-2)*(l-1)*l//6<=k-b: l+=1 l-=1 b+=(l-2)*(l-1)*l//6 for m in range(i): a[m]+=[0]*(l-2) for m in range(l-2): a.append([0]*(i+l-2)) for m in range(i-2,i-2+l): for n in range(i-2,i-2+l): a[m][n]=1 i+=l-2 for j in range(i): a[j][j]=0 print(i) for j in a: print(''.join([str(l) for l in j])) ```
output
1
32,009
13
64,019
Provide tags and a correct Python 3 solution for this coding contest problem. John Doe started thinking about graphs. After some thought he decided that he wants to paint an undirected graph, containing exactly k cycles of length 3. A cycle of length 3 is an unordered group of three distinct graph vertices a, b and c, such that each pair of them is connected by a graph edge. John has been painting for long, but he has not been a success. Help him find such graph. Note that the number of vertices there shouldn't exceed 100, or else John will have problems painting it. Input A single line contains an integer k (1 ≤ k ≤ 105) — the number of cycles of length 3 in the required graph. Output In the first line print integer n (3 ≤ n ≤ 100) — the number of vertices in the found graph. In each of next n lines print n characters "0" and "1": the i-th character of the j-th line should equal "0", if vertices i and j do not have an edge between them, otherwise it should equal "1". Note that as the required graph is undirected, the i-th character of the j-th line must equal the j-th character of the i-th line. The graph shouldn't contain self-loops, so the i-th character of the i-th line must equal "0" for all i. Examples Input 1 Output 3 011 101 110 Input 10 Output 5 01111 10111 11011 11101 11110
instruction
0
32,010
13
64,020
Tags: binary search, constructive algorithms, graphs, greedy Correct Solution: ``` # Author : nitish420 -------------------------------------------------------------------- import os import sys from io import BytesIO, IOBase def main(): k=int(input()) l=3 r=100 while l<=r : n=l+((r-l)>>1) if (n*(n-1)*(n-2))//6 <= k: l=n+1 else: r=n-1 n=l-1 ans=[[0 for _ in range(100)] for _ in range(100)] for i in range(n): for j in range(i+1,n): ans[i][j]=ans[j][i]=1 k-=(n*(n-1)*(n-2))//6 while k>0: z=2 while ((z+1)*z)>>1 <=k: z+=1 k-=((z*(z-1))>>1) n+=1 for i in range(z): ans[i][n]=ans[n][i]=1 print(n+1) for i in range(n+1): print(*(ans[i][:n+1]),sep="") #---------------------------------------------------------------------------------------- # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = 'x' in file.mode or 'r' not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b'\n') + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode('ascii')) self.read = lambda: self.buffer.read().decode('ascii') self.readline = lambda: self.buffer.readline().decode('ascii') sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip('\r\n') # endregion if __name__ == '__main__': main() ```
output
1
32,010
13
64,021
Provide tags and a correct Python 3 solution for this coding contest problem. John Doe started thinking about graphs. After some thought he decided that he wants to paint an undirected graph, containing exactly k cycles of length 3. A cycle of length 3 is an unordered group of three distinct graph vertices a, b and c, such that each pair of them is connected by a graph edge. John has been painting for long, but he has not been a success. Help him find such graph. Note that the number of vertices there shouldn't exceed 100, or else John will have problems painting it. Input A single line contains an integer k (1 ≤ k ≤ 105) — the number of cycles of length 3 in the required graph. Output In the first line print integer n (3 ≤ n ≤ 100) — the number of vertices in the found graph. In each of next n lines print n characters "0" and "1": the i-th character of the j-th line should equal "0", if vertices i and j do not have an edge between them, otherwise it should equal "1". Note that as the required graph is undirected, the i-th character of the j-th line must equal the j-th character of the i-th line. The graph shouldn't contain self-loops, so the i-th character of the i-th line must equal "0" for all i. Examples Input 1 Output 3 011 101 110 Input 10 Output 5 01111 10111 11011 11101 11110
instruction
0
32,011
13
64,022
Tags: binary search, constructive algorithms, graphs, greedy Correct Solution: ``` n = int( input() ) a = [] MAXN = 100 for i in range(MAXN): a.append( [0]*MAXN ) for i in range(3): for j in range(3): if i != j: a[i][j] = 1 cycles = 1 if cycles != n: for i in range(3,MAXN): if cycles == n: break a[i][0] = a[0][i] = 1 a[i][1] = a[1][i] = 1 cycles += 1 if cycles == n: break how = 2 for j in range(2,i): if a[i][j] == 1: continue if j != i: if cycles + how <= n: a[i][j] = a[j][i] = 1 cycles += how how += 1 if cycles == n: break print(MAXN) for i in range( len(a) ): for j in a[i]: print( j, end='') print() ```
output
1
32,011
13
64,023
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. John Doe started thinking about graphs. After some thought he decided that he wants to paint an undirected graph, containing exactly k cycles of length 3. A cycle of length 3 is an unordered group of three distinct graph vertices a, b and c, such that each pair of them is connected by a graph edge. John has been painting for long, but he has not been a success. Help him find such graph. Note that the number of vertices there shouldn't exceed 100, or else John will have problems painting it. Input A single line contains an integer k (1 ≤ k ≤ 105) — the number of cycles of length 3 in the required graph. Output In the first line print integer n (3 ≤ n ≤ 100) — the number of vertices in the found graph. In each of next n lines print n characters "0" and "1": the i-th character of the j-th line should equal "0", if vertices i and j do not have an edge between them, otherwise it should equal "1". Note that as the required graph is undirected, the i-th character of the j-th line must equal the j-th character of the i-th line. The graph shouldn't contain self-loops, so the i-th character of the i-th line must equal "0" for all i. Examples Input 1 Output 3 011 101 110 Input 10 Output 5 01111 10111 11011 11101 11110 Submitted Solution: ``` n = 100 g = [set() for i in range(n)] k = int(input()) ans = 0 flag = False for l in range(n): for r in range(l + 1): if l == r or l in g[r]: continue count = 0 for u in range(n): if u == l or u == r: continue if l in g[u] and r in g[u]: count += 1 if count + ans <= k: ans += count g[l].add(r) g[r].add(l) if ans == k: flag = True break if flag: break ans = [[0 for i in range(n)] for j in range(n)] print(100) for i in range(n): for j in range(n): if j in g[i]: ans[i][j] = 1 print(*ans[i], sep='') ```
instruction
0
32,012
13
64,024
Yes
output
1
32,012
13
64,025
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. John Doe started thinking about graphs. After some thought he decided that he wants to paint an undirected graph, containing exactly k cycles of length 3. A cycle of length 3 is an unordered group of three distinct graph vertices a, b and c, such that each pair of them is connected by a graph edge. John has been painting for long, but he has not been a success. Help him find such graph. Note that the number of vertices there shouldn't exceed 100, or else John will have problems painting it. Input A single line contains an integer k (1 ≤ k ≤ 105) — the number of cycles of length 3 in the required graph. Output In the first line print integer n (3 ≤ n ≤ 100) — the number of vertices in the found graph. In each of next n lines print n characters "0" and "1": the i-th character of the j-th line should equal "0", if vertices i and j do not have an edge between them, otherwise it should equal "1". Note that as the required graph is undirected, the i-th character of the j-th line must equal the j-th character of the i-th line. The graph shouldn't contain self-loops, so the i-th character of the i-th line must equal "0" for all i. Examples Input 1 Output 3 011 101 110 Input 10 Output 5 01111 10111 11011 11101 11110 Submitted Solution: ``` k = int(input()) p = [['0'] * 100 for j in range(100)] i, n = 0, 0 g = lambda n: n * (n * n - 1) // 6 while g(n + 1) <= k: n += 1 while i < n + 1: for j in range(i): p[i][j] = p[j][i] = '1' i += 1 k -= g(n) g = lambda n: n * (n - 1) // 2 while k: n = 0 while g(n + 1) <= k: n += 1 for j in range(n): p[i][j] = p[j][i] = '1' k -= g(n) i += 1 print(i) for j in range(i): print(''.join(p[j][:i])) ```
instruction
0
32,013
13
64,026
Yes
output
1
32,013
13
64,027
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. John Doe started thinking about graphs. After some thought he decided that he wants to paint an undirected graph, containing exactly k cycles of length 3. A cycle of length 3 is an unordered group of three distinct graph vertices a, b and c, such that each pair of them is connected by a graph edge. John has been painting for long, but he has not been a success. Help him find such graph. Note that the number of vertices there shouldn't exceed 100, or else John will have problems painting it. Input A single line contains an integer k (1 ≤ k ≤ 105) — the number of cycles of length 3 in the required graph. Output In the first line print integer n (3 ≤ n ≤ 100) — the number of vertices in the found graph. In each of next n lines print n characters "0" and "1": the i-th character of the j-th line should equal "0", if vertices i and j do not have an edge between them, otherwise it should equal "1". Note that as the required graph is undirected, the i-th character of the j-th line must equal the j-th character of the i-th line. The graph shouldn't contain self-loops, so the i-th character of the i-th line must equal "0" for all i. Examples Input 1 Output 3 011 101 110 Input 10 Output 5 01111 10111 11011 11101 11110 Submitted Solution: ``` n = int( input() ) a = [] MAXN = 100 for i in range(MAXN): a.append( [0]*MAXN ) for i in range(3): for j in range(3): if i != j: a[i][j] = 1 cycles = 1 if cycles != n: for i in range(3,MAXN): if cycles == n: break a[i][0] = a[0][i] = 1 a[i][1] = a[1][i] = 1 cycles += 1 if cycles == n: break for j in range(2,MAXN): a[i][j] = a[j][i] = 1 cycles += 1 if cycles == n: break print(MAXN) for i in range( len(a) ): for j in a[i]: print( j, end='') print() ```
instruction
0
32,014
13
64,028
No
output
1
32,014
13
64,029
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. John Doe started thinking about graphs. After some thought he decided that he wants to paint an undirected graph, containing exactly k cycles of length 3. A cycle of length 3 is an unordered group of three distinct graph vertices a, b and c, such that each pair of them is connected by a graph edge. John has been painting for long, but he has not been a success. Help him find such graph. Note that the number of vertices there shouldn't exceed 100, or else John will have problems painting it. Input A single line contains an integer k (1 ≤ k ≤ 105) — the number of cycles of length 3 in the required graph. Output In the first line print integer n (3 ≤ n ≤ 100) — the number of vertices in the found graph. In each of next n lines print n characters "0" and "1": the i-th character of the j-th line should equal "0", if vertices i and j do not have an edge between them, otherwise it should equal "1". Note that as the required graph is undirected, the i-th character of the j-th line must equal the j-th character of the i-th line. The graph shouldn't contain self-loops, so the i-th character of the i-th line must equal "0" for all i. Examples Input 1 Output 3 011 101 110 Input 10 Output 5 01111 10111 11011 11101 11110 Submitted Solution: ``` n = int( input() ) a = [] MAXN = 100 for i in range(MAXN): a.append( [0]*MAXN ) for i in range(3): for j in range(3): if i != j: a[i][j] = 1 cycles = 1 if cycles != n: for i in range(3,MAXN): if cycles == n: break a[i][0] = a[0][i] = 1 a[i][1] = a[1][i] = 1 cycles += 1 if cycles == n: break for j in range(2,MAXN): a[i][j] = a[j][i] = 1 cycles += 1 if cycles == n: break for i in range( len(a) ): for j in a[i]: print( j, end='') print() ```
instruction
0
32,015
13
64,030
No
output
1
32,015
13
64,031
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. John Doe started thinking about graphs. After some thought he decided that he wants to paint an undirected graph, containing exactly k cycles of length 3. A cycle of length 3 is an unordered group of three distinct graph vertices a, b and c, such that each pair of them is connected by a graph edge. John has been painting for long, but he has not been a success. Help him find such graph. Note that the number of vertices there shouldn't exceed 100, or else John will have problems painting it. Input A single line contains an integer k (1 ≤ k ≤ 105) — the number of cycles of length 3 in the required graph. Output In the first line print integer n (3 ≤ n ≤ 100) — the number of vertices in the found graph. In each of next n lines print n characters "0" and "1": the i-th character of the j-th line should equal "0", if vertices i and j do not have an edge between them, otherwise it should equal "1". Note that as the required graph is undirected, the i-th character of the j-th line must equal the j-th character of the i-th line. The graph shouldn't contain self-loops, so the i-th character of the i-th line must equal "0" for all i. Examples Input 1 Output 3 011 101 110 Input 10 Output 5 01111 10111 11011 11101 11110 Submitted Solution: ``` n = int( input() ) a = [] MAXN = 100 for i in range(MAXN): a.append( [0]*MAXN ) for i in range(3): for j in range(3): if i != j: a[i][j] = 1 cycles = 1 if cycles != n: for i in range(3,MAXN): if cycles == n: break a[i][0] = a[0][i] = 1 a[i][1] = a[1][i] = 1 cycles += 1 if cycles == n: break how = 2 for j in range(2,MAXN): if j != i: if cycles + how <= n: a[i][j] = a[j][i] = 1 cycles += how how += 1 if cycles == n: break else: break print(MAXN) for i in range( len(a) ): for j in a[i]: print( j, end='') print() ```
instruction
0
32,016
13
64,032
No
output
1
32,016
13
64,033
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. John Doe started thinking about graphs. After some thought he decided that he wants to paint an undirected graph, containing exactly k cycles of length 3. A cycle of length 3 is an unordered group of three distinct graph vertices a, b and c, such that each pair of them is connected by a graph edge. John has been painting for long, but he has not been a success. Help him find such graph. Note that the number of vertices there shouldn't exceed 100, or else John will have problems painting it. Input A single line contains an integer k (1 ≤ k ≤ 105) — the number of cycles of length 3 in the required graph. Output In the first line print integer n (3 ≤ n ≤ 100) — the number of vertices in the found graph. In each of next n lines print n characters "0" and "1": the i-th character of the j-th line should equal "0", if vertices i and j do not have an edge between them, otherwise it should equal "1". Note that as the required graph is undirected, the i-th character of the j-th line must equal the j-th character of the i-th line. The graph shouldn't contain self-loops, so the i-th character of the i-th line must equal "0" for all i. Examples Input 1 Output 3 011 101 110 Input 10 Output 5 01111 10111 11011 11101 11110 Submitted Solution: ``` import sys c=int(input()) Ans=[] for i in range(100): Ans.append([0]*100) print(100) cycles=0 for i in range(100): for j in range(i+1,100): for k in range(j+1,100): Ans[i][j]=1 Ans[j][i]=1 Ans[i][k]=1 Ans[k][i]=1 Ans[j][k]=1 Ans[k][j]=1 cycles+=1 if(cycles==c): break if(cycles==c): break if(cycles==c): break A="" for i in range(100): for j in range(100): A+=str(Ans[i][j]) A+="\n" sys.stdout.write(A) ```
instruction
0
32,017
13
64,034
No
output
1
32,017
13
64,035
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You have a rooted tree consisting of n vertices. Each vertex of the tree has some color. We will assume that the tree vertices are numbered by integers from 1 to n. Then we represent the color of vertex v as cv. The tree root is a vertex with number 1. In this problem you need to answer to m queries. Each query is described by two integers vj, kj. The answer to query vj, kj is the number of such colors of vertices x, that the subtree of vertex vj contains at least kj vertices of color x. You can find the definition of a rooted tree by the following link: http://en.wikipedia.org/wiki/Tree_(graph_theory). Input The first line contains two integers n and m (2 ≤ n ≤ 105; 1 ≤ m ≤ 105). The next line contains a sequence of integers c1, c2, ..., cn (1 ≤ ci ≤ 105). The next n - 1 lines contain the edges of the tree. The i-th line contains the numbers ai, bi (1 ≤ ai, bi ≤ n; ai ≠ bi) — the vertices connected by an edge of the tree. Next m lines contain the queries. The j-th line contains two integers vj, kj (1 ≤ vj ≤ n; 1 ≤ kj ≤ 105). Output Print m integers — the answers to the queries in the order the queries appear in the input. Examples Input 8 5 1 2 2 3 3 2 3 3 1 2 1 5 2 3 2 4 5 6 5 7 5 8 1 2 1 3 1 4 2 3 5 3 Output 2 2 1 0 1 Input 4 1 1 2 3 4 1 2 2 3 3 4 1 1 Output 4 Note A subtree of vertex v in a rooted tree with root r is a set of vertices {u : dist(r, v) + dist(v, u) = dist(r, u)}. Where dist(x, y) is the length (in edges) of the shortest path between vertices x and y. Submitted Solution: ``` from collections import deque n,m = [int(i) for i in input().split()] c = [int(i) for i in input().split()] a,b,end = [],{},deque() color = [] for i in range(n): color.append({}) for i in range(n - 1): P,S = [int(i) for i in input().split()] p = min(P,S) s = max(P,S) a.append(p) b[s] = p for i in b.keys(): if i not in a: end.append(i) for i in range(len(c)): color[i][c[i]] = 1 while len(end): i = end.popleft() if i in b.keys(): t = i i = b[i] for j in color[t - 1].keys(): color[i - 1][j] = color[t - 1][j] + color[i - 1].setdefault(j,0) if i not in end: end.append(i) ans = [] for i in range(m): cnt = 0 v,k = [int(i) for i in input().split()] for j in color[v - 1].keys(): if color[v - 1][j] >= k: cnt += 1 ans.append(cnt) print(color) print(*ans, sep = '\n') ```
instruction
0
32,023
13
64,046
No
output
1
32,023
13
64,047
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You have a rooted tree consisting of n vertices. Each vertex of the tree has some color. We will assume that the tree vertices are numbered by integers from 1 to n. Then we represent the color of vertex v as cv. The tree root is a vertex with number 1. In this problem you need to answer to m queries. Each query is described by two integers vj, kj. The answer to query vj, kj is the number of such colors of vertices x, that the subtree of vertex vj contains at least kj vertices of color x. You can find the definition of a rooted tree by the following link: http://en.wikipedia.org/wiki/Tree_(graph_theory). Input The first line contains two integers n and m (2 ≤ n ≤ 105; 1 ≤ m ≤ 105). The next line contains a sequence of integers c1, c2, ..., cn (1 ≤ ci ≤ 105). The next n - 1 lines contain the edges of the tree. The i-th line contains the numbers ai, bi (1 ≤ ai, bi ≤ n; ai ≠ bi) — the vertices connected by an edge of the tree. Next m lines contain the queries. The j-th line contains two integers vj, kj (1 ≤ vj ≤ n; 1 ≤ kj ≤ 105). Output Print m integers — the answers to the queries in the order the queries appear in the input. Examples Input 8 5 1 2 2 3 3 2 3 3 1 2 1 5 2 3 2 4 5 6 5 7 5 8 1 2 1 3 1 4 2 3 5 3 Output 2 2 1 0 1 Input 4 1 1 2 3 4 1 2 2 3 3 4 1 1 Output 4 Note A subtree of vertex v in a rooted tree with root r is a set of vertices {u : dist(r, v) + dist(v, u) = dist(r, u)}. Where dist(x, y) is the length (in edges) of the shortest path between vertices x and y. Submitted Solution: ``` from sys import stdin n,m = [int(i) for i in stdin.readline().split()] c = [int(i) for i in stdin.readline().split()] d = {} for _ in range(n-1): a,b = [int(i) for i in stdin.readline().split()] d[a] = d.get(a,[]) + [b] re = [] for _ in range(m): cnt = {} v,k = [int(i) for i in stdin.readline().split()] temp = [v] while len(temp) != 0: l = [] for i in temp: cnt[c[i-1]] = cnt.get(c[i-1],0) + 1 l += d.get(i,[]) temp = l r = 0 #print(cnt) for i in cnt.values(): if i >= k: r += 1 re.append(str(r)) print('\n'.join(re)) ```
instruction
0
32,024
13
64,048
No
output
1
32,024
13
64,049
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You have a rooted tree consisting of n vertices. Each vertex of the tree has some color. We will assume that the tree vertices are numbered by integers from 1 to n. Then we represent the color of vertex v as cv. The tree root is a vertex with number 1. In this problem you need to answer to m queries. Each query is described by two integers vj, kj. The answer to query vj, kj is the number of such colors of vertices x, that the subtree of vertex vj contains at least kj vertices of color x. You can find the definition of a rooted tree by the following link: http://en.wikipedia.org/wiki/Tree_(graph_theory). Input The first line contains two integers n and m (2 ≤ n ≤ 105; 1 ≤ m ≤ 105). The next line contains a sequence of integers c1, c2, ..., cn (1 ≤ ci ≤ 105). The next n - 1 lines contain the edges of the tree. The i-th line contains the numbers ai, bi (1 ≤ ai, bi ≤ n; ai ≠ bi) — the vertices connected by an edge of the tree. Next m lines contain the queries. The j-th line contains two integers vj, kj (1 ≤ vj ≤ n; 1 ≤ kj ≤ 105). Output Print m integers — the answers to the queries in the order the queries appear in the input. Examples Input 8 5 1 2 2 3 3 2 3 3 1 2 1 5 2 3 2 4 5 6 5 7 5 8 1 2 1 3 1 4 2 3 5 3 Output 2 2 1 0 1 Input 4 1 1 2 3 4 1 2 2 3 3 4 1 1 Output 4 Note A subtree of vertex v in a rooted tree with root r is a set of vertices {u : dist(r, v) + dist(v, u) = dist(r, u)}. Where dist(x, y) is the length (in edges) of the shortest path between vertices x and y. Submitted Solution: ``` n, m = input().split(' ') n, m = int(n), int(m) i = 0 u = dict() c = input().split(' ') for i in range(0, n): c[i] = int(c[i]) for i in range(0, n-1): From, To = input().split(' ') From, To = int(From), int(To) if From == To: continue if From not in u: u[From] = list() u[From].append(To) #print(u) for i in range(0, m): v, k = input().split(' ') v, k = int(v), int(k) Q = list() C = dict() Q.append(v) Count = 0 Counted = set() while Q: # print(Q) t = Q.pop() if c[t-1] not in C: C[c[t-1]] = 0 C[c[t-1]] += 1 if (C[c[t-1]] >= k) and (c[t-1] not in Counted): Count += 1 Counted.add(c[t-1]) if t not in u: continue # print(Q) # print(C) #print(Count) Q.extend(u[t]) print(Count) ```
instruction
0
32,025
13
64,050
No
output
1
32,025
13
64,051
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You have a rooted tree consisting of n vertices. Each vertex of the tree has some color. We will assume that the tree vertices are numbered by integers from 1 to n. Then we represent the color of vertex v as cv. The tree root is a vertex with number 1. In this problem you need to answer to m queries. Each query is described by two integers vj, kj. The answer to query vj, kj is the number of such colors of vertices x, that the subtree of vertex vj contains at least kj vertices of color x. You can find the definition of a rooted tree by the following link: http://en.wikipedia.org/wiki/Tree_(graph_theory). Input The first line contains two integers n and m (2 ≤ n ≤ 105; 1 ≤ m ≤ 105). The next line contains a sequence of integers c1, c2, ..., cn (1 ≤ ci ≤ 105). The next n - 1 lines contain the edges of the tree. The i-th line contains the numbers ai, bi (1 ≤ ai, bi ≤ n; ai ≠ bi) — the vertices connected by an edge of the tree. Next m lines contain the queries. The j-th line contains two integers vj, kj (1 ≤ vj ≤ n; 1 ≤ kj ≤ 105). Output Print m integers — the answers to the queries in the order the queries appear in the input. Examples Input 8 5 1 2 2 3 3 2 3 3 1 2 1 5 2 3 2 4 5 6 5 7 5 8 1 2 1 3 1 4 2 3 5 3 Output 2 2 1 0 1 Input 4 1 1 2 3 4 1 2 2 3 3 4 1 1 Output 4 Note A subtree of vertex v in a rooted tree with root r is a set of vertices {u : dist(r, v) + dist(v, u) = dist(r, u)}. Where dist(x, y) is the length (in edges) of the shortest path between vertices x and y. Submitted Solution: ``` n, m = map(int, input().split()) c = list(map(int, input().split())) g = [[] for i in range(n)] for i in range(n-1): a, b = map(int, input().split()) a, b = a-1, b-1 g[a].append(b) g[b].append(a) ans = [0 for i in range(m)] q = [[] for i in range(n)] u = [0 for i in range(n)] for i in range(m): v, k = map(int, input().split()) q[v-1].append((k, i)) def add(a, x, d): i = x while i <= n: if not i in a: a[i] = 0 a[i] += d i += i & -i def query(a, x): i = x s = 0 while i > 0: if i in a: s += a[i] i -= i & -i return s def merge(a, b): if len(a[0]) < len(b[0]): a, b = b, a for c, y in b[0].items(): y0 = (a[0][c] if c in a[0] else 0) a[0][c] = y0 + y if y0: add(a[1], y0, -1) add(a[1], y0 + y, 1) return a def dfs(x): u[x] = 1 tmp = ({c[x]: 1}, {}) add(tmp[1], 1, 1) l = [tmp] for y in g[x]: if not u[y]: l.append(dfs(y)) while len(l) > 1: l2 = [] for i in range(len(l)//2): l2.append(merge(l[2*i], l[2*i+1])) if len(l) % 2: l2.append(l[-1]) l = l2 l = l[0] for k, i in q[x]: ans[i] = len(l[0]) - query(l[1], k-1) return l dfs(0) print('\n'.join(map(str, ans))) ```
instruction
0
32,026
13
64,052
No
output
1
32,026
13
64,053
Provide a correct Python 3 solution for this coding contest problem. We have a graph with N vertices, numbered 0 through N-1. Edges are yet to be added. We will process Q queries to add edges. In the i-th (1≦i≦Q) query, three integers A_i, B_i and C_i will be given, and we will add infinitely many edges to the graph as follows: * The two vertices numbered A_i and B_i will be connected by an edge with a weight of C_i. * The two vertices numbered B_i and A_i+1 will be connected by an edge with a weight of C_i+1. * The two vertices numbered A_i+1 and B_i+1 will be connected by an edge with a weight of C_i+2. * The two vertices numbered B_i+1 and A_i+2 will be connected by an edge with a weight of C_i+3. * The two vertices numbered A_i+2 and B_i+2 will be connected by an edge with a weight of C_i+4. * The two vertices numbered B_i+2 and A_i+3 will be connected by an edge with a weight of C_i+5. * The two vertices numbered A_i+3 and B_i+3 will be connected by an edge with a weight of C_i+6. * ... Here, consider the indices of the vertices modulo N. For example, the vertice numbered N is the one numbered 0, and the vertice numbered 2N-1 is the one numbered N-1. The figure below shows the first seven edges added when N=16, A_i=7, B_i=14, C_i=1: <image> After processing all the queries, find the total weight of the edges contained in a minimum spanning tree of the graph. Constraints * 2≦N≦200,000 * 1≦Q≦200,000 * 0≦A_i,B_i≦N-1 * 1≦C_i≦10^9 Input The input is given from Standard Input in the following format: N Q A_1 B_1 C_1 A_2 B_2 C_2 : A_Q B_Q C_Q Output Print the total weight of the edges contained in a minimum spanning tree of the graph. Examples Input 7 1 5 2 1 Output 21 Input 2 1 0 0 1000000000 Output 1000000001 Input 5 3 0 1 10 0 2 10 0 4 10 Output 42
instruction
0
32,383
13
64,766
"Correct Solution: ``` import sys read = sys.stdin.buffer.read readline = sys.stdin.buffer.readline readlines = sys.stdin.buffer.readlines from operator import itemgetter N,Q = map(int,readline().split()) m = map(int,read().split()) ABC = list(zip(m,m,m)) INF = 10 ** 18 cyclic_cost = [INF] * N for a,b,c in ABC: if cyclic_cost[a] > c + 1: cyclic_cost[a] = c + 1 if cyclic_cost[b] > c + 2: cyclic_cost[b] = c + 2 cyclic_cost += cyclic_cost # 2周分 x = INF for i in range(N+N): x += 2 if x < cyclic_cost[i]: cyclic_cost[i] = x x = cyclic_cost[i] cyclic_cost = [x if x < y else y for x,y in zip(cyclic_cost, cyclic_cost[N:])] ABC += [(i,i+1,c) for i,c in enumerate(cyclic_cost)] ABC[-1] = (N-1,0,cyclic_cost[-1]) class UnionFind: def __init__(self,N): self.root = list(range(N)) self.size = [1] * (N) def find_root(self,x): root = self.root while root[x] != x: root[x] = root[root[x]] x = root[x] return x def merge(self,x,y): x = self.find_root(x) y = self.find_root(y) if x == y: return False sx,sy = self.size[x],self.size[y] if sx < sy: self.root[x] = y self.size[y] += sx else: self.root[y] = x self.size[x] += sy return True ABC.sort(key = itemgetter(2)) uf = UnionFind(N) merge = uf.merge answer = 0 for a,b,c in ABC: if merge(a,b): answer += c print(answer) ```
output
1
32,383
13
64,767
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. We have a graph with N vertices, numbered 0 through N-1. Edges are yet to be added. We will process Q queries to add edges. In the i-th (1≦i≦Q) query, three integers A_i, B_i and C_i will be given, and we will add infinitely many edges to the graph as follows: * The two vertices numbered A_i and B_i will be connected by an edge with a weight of C_i. * The two vertices numbered B_i and A_i+1 will be connected by an edge with a weight of C_i+1. * The two vertices numbered A_i+1 and B_i+1 will be connected by an edge with a weight of C_i+2. * The two vertices numbered B_i+1 and A_i+2 will be connected by an edge with a weight of C_i+3. * The two vertices numbered A_i+2 and B_i+2 will be connected by an edge with a weight of C_i+4. * The two vertices numbered B_i+2 and A_i+3 will be connected by an edge with a weight of C_i+5. * The two vertices numbered A_i+3 and B_i+3 will be connected by an edge with a weight of C_i+6. * ... Here, consider the indices of the vertices modulo N. For example, the vertice numbered N is the one numbered 0, and the vertice numbered 2N-1 is the one numbered N-1. The figure below shows the first seven edges added when N=16, A_i=7, B_i=14, C_i=1: <image> After processing all the queries, find the total weight of the edges contained in a minimum spanning tree of the graph. Constraints * 2≦N≦200,000 * 1≦Q≦200,000 * 0≦A_i,B_i≦N-1 * 1≦C_i≦10^9 Input The input is given from Standard Input in the following format: N Q A_1 B_1 C_1 A_2 B_2 C_2 : A_Q B_Q C_Q Output Print the total weight of the edges contained in a minimum spanning tree of the graph. Examples Input 7 1 5 2 1 Output 21 Input 2 1 0 0 1000000000 Output 1000000001 Input 5 3 0 1 10 0 2 10 0 4 10 Output 42 Submitted Solution: ``` import sys input = sys.stdin.readline import heapq n, q = [ int(v) for v in input().split() ] parent_list = [ i for i in range(n) ] def root(x): compress_node = [] while parent_list[x] != x: compress_node.append(x) x = parent_list[x] for i in compress_node: parent_list[i] = x return x query_list = [] for i in range(q): a, b, c = [ int(v) for v in input().split() ] query_list.append([c,a,b]) query_list.sort() connect = 0 ans = 0 #while connect != n-1: for i in range(20): c, a, b = heapq.heappop(query_list) ra, rb = root(a), root(b) if ra != rb: parent_list[ra] = b connect += 1 ans += c heapq.heappush(query_list, [c+1,b%n,(a+1)%n]) print(ans) ```
instruction
0
32,384
13
64,768
No
output
1
32,384
13
64,769
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. We have a graph with N vertices, numbered 0 through N-1. Edges are yet to be added. We will process Q queries to add edges. In the i-th (1≦i≦Q) query, three integers A_i, B_i and C_i will be given, and we will add infinitely many edges to the graph as follows: * The two vertices numbered A_i and B_i will be connected by an edge with a weight of C_i. * The two vertices numbered B_i and A_i+1 will be connected by an edge with a weight of C_i+1. * The two vertices numbered A_i+1 and B_i+1 will be connected by an edge with a weight of C_i+2. * The two vertices numbered B_i+1 and A_i+2 will be connected by an edge with a weight of C_i+3. * The two vertices numbered A_i+2 and B_i+2 will be connected by an edge with a weight of C_i+4. * The two vertices numbered B_i+2 and A_i+3 will be connected by an edge with a weight of C_i+5. * The two vertices numbered A_i+3 and B_i+3 will be connected by an edge with a weight of C_i+6. * ... Here, consider the indices of the vertices modulo N. For example, the vertice numbered N is the one numbered 0, and the vertice numbered 2N-1 is the one numbered N-1. The figure below shows the first seven edges added when N=16, A_i=7, B_i=14, C_i=1: <image> After processing all the queries, find the total weight of the edges contained in a minimum spanning tree of the graph. Constraints * 2≦N≦200,000 * 1≦Q≦200,000 * 0≦A_i,B_i≦N-1 * 1≦C_i≦10^9 Input The input is given from Standard Input in the following format: N Q A_1 B_1 C_1 A_2 B_2 C_2 : A_Q B_Q C_Q Output Print the total weight of the edges contained in a minimum spanning tree of the graph. Examples Input 7 1 5 2 1 Output 21 Input 2 1 0 0 1000000000 Output 1000000001 Input 5 3 0 1 10 0 2 10 0 4 10 Output 42 Submitted Solution: ``` import sys input = sys.stdin.readline import heapq n, q = [ int(v) for v in input().split() ] parent_list = [ i for i in range(n) ] def root(x): compress_node = [] while parent_list[x] != x: compress_node.append(x) x = parent_list[x] for i in compress_node: parent_list[i] = x return x query_list = [] for i in range(q): a, b, c = [ int(v) for v in input().split() ] query_list.append([c,a,b]) query_list.sort() connect = 0 ans = 0 while connect != n-1: c, a, b = heapq.heappop(query_list) ra, rb = root(a), root(b) if ra != rb: parent_list[ra] = b connect += 1 ans += c heapq.heappush(query_list, [c+1,b%n,(a+1)%n]) print(ans) ```
instruction
0
32,385
13
64,770
No
output
1
32,385
13
64,771
Provide a correct Python 3 solution for this coding contest problem. For a given weighted graph $G = (V, E)$, find the shortest path from a source to each vertex. For each vertex $u$, print the total weight of edges on the shortest path from vertex $0$ to $u$. Constraints * $1 \leq n \leq 10,000$ * $0 \leq c_i \leq 100,000$ * $|E| < 500,000$ * All vertices are reachable from vertex $0$ Input In the first line, an integer $n$ denoting the number of vertices in $G$ is given. In the following $n$ lines, adjacency lists for each vertex $u$ are respectively given in the following format: $u$ $k$ $v_1$ $c_1$ $v_2$ $c_2$ ... $v_k$ $c_k$ Vertices in $G$ are named with IDs $0, 1, ..., n-1$. $u$ is ID of the target vertex and $k$ denotes its degree. $v_i (i = 1, 2, ... k)$ denote IDs of vertices adjacent to $u$ and $c_i$ denotes the weight of a directed edge connecting $u$ and $v_i$ (from $u$ to $v_i$). Output For each vertex, print its ID and the distance separated by a space character in a line respectively. Print in order of vertex IDs. Example Input 5 0 3 2 3 3 1 1 2 1 2 0 2 3 4 2 3 0 3 3 1 4 1 3 4 2 1 0 1 1 4 4 3 4 2 2 1 3 3 Output 0 0 1 2 2 2 3 1 4 3
instruction
0
32,460
13
64,920
"Correct Solution: ``` import sys f_i = sys.stdin n = int(f_i.readline()) class VCost: def __init__(self, v, cost): self.v_n = v self.cost = cost def __lt__(self, other): return self.cost < other.cost def __gt__(self, other): return self.cost > other.cost adj = [[VCost(int(v), int(c)) for v, c in zip(x.split()[2::2], x.split()[3::2])] for x in f_i] import heapq def dijkstra(): PQ = [] isVisited = [False] * n distance = [999900001] * n distance[0] = 0 heapq.heappush(PQ, VCost(0, 0)) while PQ: uc = heapq.heappop(PQ) u = uc.v_n if uc.cost > distance[uc.v_n]: continue isVisited[u] = True for vc in adj[u]: v = vc.v_n if isVisited[v] == True: continue t_cost = distance[u] + vc.cost if t_cost < distance[v]: distance[v] = t_cost = distance[u] + vc.cost heapq.heappush(PQ, VCost(v, t_cost)) for v, d in enumerate(distance): print(v, d) dijkstra() ```
output
1
32,460
13
64,921
Provide a correct Python 3 solution for this coding contest problem. For a given weighted graph $G = (V, E)$, find the shortest path from a source to each vertex. For each vertex $u$, print the total weight of edges on the shortest path from vertex $0$ to $u$. Constraints * $1 \leq n \leq 10,000$ * $0 \leq c_i \leq 100,000$ * $|E| < 500,000$ * All vertices are reachable from vertex $0$ Input In the first line, an integer $n$ denoting the number of vertices in $G$ is given. In the following $n$ lines, adjacency lists for each vertex $u$ are respectively given in the following format: $u$ $k$ $v_1$ $c_1$ $v_2$ $c_2$ ... $v_k$ $c_k$ Vertices in $G$ are named with IDs $0, 1, ..., n-1$. $u$ is ID of the target vertex and $k$ denotes its degree. $v_i (i = 1, 2, ... k)$ denote IDs of vertices adjacent to $u$ and $c_i$ denotes the weight of a directed edge connecting $u$ and $v_i$ (from $u$ to $v_i$). Output For each vertex, print its ID and the distance separated by a space character in a line respectively. Print in order of vertex IDs. Example Input 5 0 3 2 3 3 1 1 2 1 2 0 2 3 4 2 3 0 3 3 1 4 1 3 4 2 1 0 1 1 4 4 3 4 2 2 1 3 3 Output 0 0 1 2 2 2 3 1 4 3
instruction
0
32,461
13
64,922
"Correct Solution: ``` # -*- coding: utf-8 -*- """ http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ALDS1_12_C ???????§????????????????II """ from enum import Enum from heapq import heappush, heappop, heapify class Sssp(object): """ single source shortest path """ INFINITY = 999999999 class Status(Enum): """ ?????????????¨??????¶??? """ white = 1 # ????¨???? gray = 2 # ?¨??????? black = 3 #?¨??????? def __init__(self, data): num_of_nodes = len(data) self.color = [Sssp.Status.white] * num_of_nodes # ????????????????¨??????¶??? self.d = [Sssp.INFINITY] * num_of_nodes # ?§??????????????????? self.p = [-1] * num_of_nodes # ????????????????????????????¨????????????????????????? self.adj = [[] for _ in range(num_of_nodes)] self.make_adj(data) def make_adj(self, data): # ??£??\?????????????????? for d in data: my_id = d[0] d = d[2:] while len(d) > 1: to_node, cost = d[0], d[1] self.adj[my_id].insert(0, (to_node, cost)) d = d[2:] def dijkstra(self, start): self.d[start] = 0 pq = [] heappush(pq, (0, 0)) while pq: cost, u = heappop(pq) self.color[u] = Sssp.Status.black if self.d[u] < cost: continue for v, cost in self.adj[u]: if self.color[v] == Sssp.Status.black: continue if self.d[v] > self.d[u] + cost: self.d[v] = self.d[u] + cost heappush(pq, (self.d[v], v)) self.color[v] = Sssp.Status.gray if __name__ == '__main__': # ??????????????\??? num = int(input()) data = [] for i in range(num): data.append(list(map(int, input().split(' ')))) # ???????????¢?´¢ s = Sssp(data) s.dijkstra(0) # ???????????¨??? for i in range(num): print('{0} {1}'.format(i, s.d[i])) ```
output
1
32,461
13
64,923
Provide a correct Python 3 solution for this coding contest problem. For a given weighted graph $G = (V, E)$, find the shortest path from a source to each vertex. For each vertex $u$, print the total weight of edges on the shortest path from vertex $0$ to $u$. Constraints * $1 \leq n \leq 10,000$ * $0 \leq c_i \leq 100,000$ * $|E| < 500,000$ * All vertices are reachable from vertex $0$ Input In the first line, an integer $n$ denoting the number of vertices in $G$ is given. In the following $n$ lines, adjacency lists for each vertex $u$ are respectively given in the following format: $u$ $k$ $v_1$ $c_1$ $v_2$ $c_2$ ... $v_k$ $c_k$ Vertices in $G$ are named with IDs $0, 1, ..., n-1$. $u$ is ID of the target vertex and $k$ denotes its degree. $v_i (i = 1, 2, ... k)$ denote IDs of vertices adjacent to $u$ and $c_i$ denotes the weight of a directed edge connecting $u$ and $v_i$ (from $u$ to $v_i$). Output For each vertex, print its ID and the distance separated by a space character in a line respectively. Print in order of vertex IDs. Example Input 5 0 3 2 3 3 1 1 2 1 2 0 2 3 4 2 3 0 3 3 1 4 1 3 4 2 1 0 1 1 4 4 3 4 2 2 1 3 3 Output 0 0 1 2 2 2 3 1 4 3
instruction
0
32,462
13
64,924
"Correct Solution: ``` #!/usr/bin/env python # -*- coding: utf-8 -*- """ input: 5 0 3 2 3 3 1 1 2 1 2 0 2 3 4 2 3 0 3 3 1 4 1 3 4 2 1 0 1 1 4 4 3 4 2 2 1 3 3 output: 0 0 1 2 2 2 3 1 4 3 """ import sys import heapq as hp WHITE, GRAY, BLACK = 0, 1, 2 D_MAX = int(5e10 + 1) def generate_adj_table(v_table): for each in v_table: v_index, v_adj_length, *v_adj_list = map(int, each) # assert len(v_adj_list) == v_adj_length * 2 for pair in zip(v_adj_list[::2], v_adj_list[1::2]): init_adj_table[v_index][pair[0]] = pair[1] return init_adj_table def dijkstra_path_heap(): # path search init path_list[init_vertex_index] = 0 path_heap = [] # heapq: rank by tuple[0], at here it's d[u] hp.heappush(path_heap, (0, init_vertex_index)) while len(path_heap) >= 1: current_vertex = hp.heappop(path_heap)[1] color[current_vertex] = BLACK for adj_vertex, adj_weight in adj_table[current_vertex].items(): if color[adj_vertex] is not BLACK: # alt: d[u] + w[u,v] alt_path = path_list[current_vertex] + adj_weight if alt_path < path_list[adj_vertex]: # update path_list path_list[adj_vertex] = alt_path # update heap hp.heappush(path_heap, (alt_path, adj_vertex)) parent_list[adj_vertex] = current_vertex color[adj_vertex] = GRAY return path_list if __name__ == '__main__': _input = sys.stdin.readlines() vertices_num = int(_input[0]) init_vertices_table = map(lambda x: x.split(), _input[1:]) # assert len(init_vertices_table) == vertices_num parent_list, path_list = [-1] * vertices_num, [D_MAX] * vertices_num color = [WHITE] * vertices_num init_adj_table = tuple(dict() for _ in range(vertices_num)) init_vertex_index = 0 adj_table = generate_adj_table(init_vertices_table) ans = dijkstra_path_heap() for i, v in enumerate(ans): print(i, v) ```
output
1
32,462
13
64,925
Provide a correct Python 3 solution for this coding contest problem. For a given weighted graph $G = (V, E)$, find the shortest path from a source to each vertex. For each vertex $u$, print the total weight of edges on the shortest path from vertex $0$ to $u$. Constraints * $1 \leq n \leq 10,000$ * $0 \leq c_i \leq 100,000$ * $|E| < 500,000$ * All vertices are reachable from vertex $0$ Input In the first line, an integer $n$ denoting the number of vertices in $G$ is given. In the following $n$ lines, adjacency lists for each vertex $u$ are respectively given in the following format: $u$ $k$ $v_1$ $c_1$ $v_2$ $c_2$ ... $v_k$ $c_k$ Vertices in $G$ are named with IDs $0, 1, ..., n-1$. $u$ is ID of the target vertex and $k$ denotes its degree. $v_i (i = 1, 2, ... k)$ denote IDs of vertices adjacent to $u$ and $c_i$ denotes the weight of a directed edge connecting $u$ and $v_i$ (from $u$ to $v_i$). Output For each vertex, print its ID and the distance separated by a space character in a line respectively. Print in order of vertex IDs. Example Input 5 0 3 2 3 3 1 1 2 1 2 0 2 3 4 2 3 0 3 3 1 4 1 3 4 2 1 0 1 1 4 4 3 4 2 2 1 3 3 Output 0 0 1 2 2 2 3 1 4 3
instruction
0
32,463
13
64,926
"Correct Solution: ``` import sys from heapq import* e=sys.stdin.readline n=int(e()) A=[[]for _ in[0]*n] for _ in[0]*n: b=list(map(int,e().split())) for i in range(b[1]):k=2*-~i;A[b[0]]+=[(b[k],b[k+1])] H=[[0,0]] d=[0]+[1e6]*n c=[1]*n while H: f=heappop(H) u=f[1] c[u]=0 if d[u]>=f[0]: for s in A[u]: v=s[0] if c[v]and d[v]>d[u]+s[1]: d[v]=d[u]+s[1] heappush(H,[d[v],v]) for i in range(n):print(i,d[i]) ```
output
1
32,463
13
64,927
Provide a correct Python 3 solution for this coding contest problem. For a given weighted graph $G = (V, E)$, find the shortest path from a source to each vertex. For each vertex $u$, print the total weight of edges on the shortest path from vertex $0$ to $u$. Constraints * $1 \leq n \leq 10,000$ * $0 \leq c_i \leq 100,000$ * $|E| < 500,000$ * All vertices are reachable from vertex $0$ Input In the first line, an integer $n$ denoting the number of vertices in $G$ is given. In the following $n$ lines, adjacency lists for each vertex $u$ are respectively given in the following format: $u$ $k$ $v_1$ $c_1$ $v_2$ $c_2$ ... $v_k$ $c_k$ Vertices in $G$ are named with IDs $0, 1, ..., n-1$. $u$ is ID of the target vertex and $k$ denotes its degree. $v_i (i = 1, 2, ... k)$ denote IDs of vertices adjacent to $u$ and $c_i$ denotes the weight of a directed edge connecting $u$ and $v_i$ (from $u$ to $v_i$). Output For each vertex, print its ID and the distance separated by a space character in a line respectively. Print in order of vertex IDs. Example Input 5 0 3 2 3 3 1 1 2 1 2 0 2 3 4 2 3 0 3 3 1 4 1 3 4 2 1 0 1 1 4 4 3 4 2 2 1 3 3 Output 0 0 1 2 2 2 3 1 4 3
instruction
0
32,464
13
64,928
"Correct Solution: ``` import heapq def dijkstra(n): inf = 10 ** 6 + 1 dist = [0] + [inf] * (n - 1) q = [(0, 0)] while q: u = heapq.heappop(q)[1] for (v, c) in edge[u]: alt = dist[u] + c if dist[v] > alt: dist[v] = alt heapq.heappush(q, (alt, v)) return dist n = int(input()) edge = [[]] * n for _ in range(n): l = list(map(int, input().split())) edge[l[0]] = (e for e in zip(l[2::2], l[3::2])) for i, c in enumerate(dijkstra(n)): print(i, c) ```
output
1
32,464
13
64,929
Provide a correct Python 3 solution for this coding contest problem. For a given weighted graph $G = (V, E)$, find the shortest path from a source to each vertex. For each vertex $u$, print the total weight of edges on the shortest path from vertex $0$ to $u$. Constraints * $1 \leq n \leq 10,000$ * $0 \leq c_i \leq 100,000$ * $|E| < 500,000$ * All vertices are reachable from vertex $0$ Input In the first line, an integer $n$ denoting the number of vertices in $G$ is given. In the following $n$ lines, adjacency lists for each vertex $u$ are respectively given in the following format: $u$ $k$ $v_1$ $c_1$ $v_2$ $c_2$ ... $v_k$ $c_k$ Vertices in $G$ are named with IDs $0, 1, ..., n-1$. $u$ is ID of the target vertex and $k$ denotes its degree. $v_i (i = 1, 2, ... k)$ denote IDs of vertices adjacent to $u$ and $c_i$ denotes the weight of a directed edge connecting $u$ and $v_i$ (from $u$ to $v_i$). Output For each vertex, print its ID and the distance separated by a space character in a line respectively. Print in order of vertex IDs. Example Input 5 0 3 2 3 3 1 1 2 1 2 0 2 3 4 2 3 0 3 3 1 4 1 3 4 2 1 0 1 1 4 4 3 4 2 2 1 3 3 Output 0 0 1 2 2 2 3 1 4 3
instruction
0
32,465
13
64,930
"Correct Solution: ``` import sys,collections N = int(sys.stdin.readline()) G = tuple(tuple(map(int,sys.stdin.readline().rstrip().split()))[2:] for _ in range(N)) # multi line with multi param # n x n adjacency matrix #G = [[-1,2,3],[2,-1,3],[1,2,-1]] INF = float("inf") ALL = set(range(N)) mst = set() distances = [INF]*N # 蟋狗せ0縺九i縺ョ霍晞屬 distances[0] = 0 parents = [INF]*N parents[0] = 0 import heapq dv = [] def add(u): mst.add(u) if not ALL-mst: return for j in range(0,len(G[u]),2): v = G[u][j] w = G[u][j+1] if not v in mst and w + distances[u] < distances[v]: # u繧堤オ檎罰縺励◆譁ケ縺悟ョ峨> distances[v] = distances[u]+w parents[v] = u heapq.heappush(dv, (distances[v],v)) #print(distances) d,v = heapq.heappop(dv) while v in mst: d,v = heapq.heappop(dv) return v n = add(0) distances[0] = 0 parents[0]=0 while len(mst) < len(G): n = add(n) for i in range(N): print(i,distances[i]) ```
output
1
32,465
13
64,931
Provide a correct Python 3 solution for this coding contest problem. For a given weighted graph $G = (V, E)$, find the shortest path from a source to each vertex. For each vertex $u$, print the total weight of edges on the shortest path from vertex $0$ to $u$. Constraints * $1 \leq n \leq 10,000$ * $0 \leq c_i \leq 100,000$ * $|E| < 500,000$ * All vertices are reachable from vertex $0$ Input In the first line, an integer $n$ denoting the number of vertices in $G$ is given. In the following $n$ lines, adjacency lists for each vertex $u$ are respectively given in the following format: $u$ $k$ $v_1$ $c_1$ $v_2$ $c_2$ ... $v_k$ $c_k$ Vertices in $G$ are named with IDs $0, 1, ..., n-1$. $u$ is ID of the target vertex and $k$ denotes its degree. $v_i (i = 1, 2, ... k)$ denote IDs of vertices adjacent to $u$ and $c_i$ denotes the weight of a directed edge connecting $u$ and $v_i$ (from $u$ to $v_i$). Output For each vertex, print its ID and the distance separated by a space character in a line respectively. Print in order of vertex IDs. Example Input 5 0 3 2 3 3 1 1 2 1 2 0 2 3 4 2 3 0 3 3 1 4 1 3 4 2 1 0 1 1 4 4 3 4 2 2 1 3 3 Output 0 0 1 2 2 2 3 1 4 3
instruction
0
32,466
13
64,932
"Correct Solution: ``` from heapq import heapify, heappush, heappop INF = float("inf") def MAIN(): n = int(input()) G = [[i, INF] for i in range(n)] G[0][1] = 0 m = {} for _ in range(n): A = list(map(int, input().split())) m[A[0]] = {} for i in range(2, len(A), 2): m[A[0]][A[i]] = A[i + 1] dp = [(0, 0)] while dp: cost, u = heappop(dp) for v, c in m[u].items(): if G[v][1] > G[u][1] + c: G[v][1] = G[u][1] + c heappush(dp, (G[v][1], v)) print("\n".join(" ".join(map(str, a)) for a in G)) MAIN() ```
output
1
32,466
13
64,933
Provide a correct Python 3 solution for this coding contest problem. For a given weighted graph $G = (V, E)$, find the shortest path from a source to each vertex. For each vertex $u$, print the total weight of edges on the shortest path from vertex $0$ to $u$. Constraints * $1 \leq n \leq 10,000$ * $0 \leq c_i \leq 100,000$ * $|E| < 500,000$ * All vertices are reachable from vertex $0$ Input In the first line, an integer $n$ denoting the number of vertices in $G$ is given. In the following $n$ lines, adjacency lists for each vertex $u$ are respectively given in the following format: $u$ $k$ $v_1$ $c_1$ $v_2$ $c_2$ ... $v_k$ $c_k$ Vertices in $G$ are named with IDs $0, 1, ..., n-1$. $u$ is ID of the target vertex and $k$ denotes its degree. $v_i (i = 1, 2, ... k)$ denote IDs of vertices adjacent to $u$ and $c_i$ denotes the weight of a directed edge connecting $u$ and $v_i$ (from $u$ to $v_i$). Output For each vertex, print its ID and the distance separated by a space character in a line respectively. Print in order of vertex IDs. Example Input 5 0 3 2 3 3 1 1 2 1 2 0 2 3 4 2 3 0 3 3 1 4 1 3 4 2 1 0 1 1 4 4 3 4 2 2 1 3 3 Output 0 0 1 2 2 2 3 1 4 3
instruction
0
32,467
13
64,934
"Correct Solution: ``` #!/usr/bin/env python # -*- coding: utf-8 -*- """ input: 5 0 3 2 3 3 1 1 2 1 2 0 2 3 4 2 3 0 3 3 1 4 1 3 4 2 1 0 1 1 4 4 3 4 2 2 1 3 3 output: 0 0 1 2 2 2 3 1 4 3 """ import sys import heapq as hp WHITE, GRAY, BLACK = 0, 1, 2 D_MAX = int(5e10 + 1) def generate_adj_table(v_table): for each in v_table: v_index, v_adj_length, *v_adj_list = map(int, each) # assert len(v_adj_list) == v_adj_length * 2 for pair in zip(v_adj_list[::2], v_adj_list[1::2]): init_adj_table[v_index][pair[0]] = pair[1] return init_adj_table def dijkstra_path_heap(): # path search init path_list[init_vertex_index] = 0 path_heap = [] # heapq: rank by tuple[0], at here it's d[u] hp.heappush(path_heap, (0, init_vertex_index)) while len(path_heap) >= 1: current_vertex = hp.heappop(path_heap)[1] color[current_vertex] = BLACK current_vertex_adjs = adj_table[current_vertex] for adj_vertex, adj_weight in current_vertex_adjs.items(): # adj_weight = current_vertex_adjs.get(adj_vertex) if color[adj_vertex] is not BLACK: # alt: d[u] + w[u,v] alt_path = path_list[current_vertex] + adj_weight if alt_path < path_list[adj_vertex]: # update path_list path_list[adj_vertex] = alt_path # update heap hp.heappush(path_heap, (alt_path, adj_vertex)) parent_list[adj_vertex] = current_vertex color[adj_vertex] = GRAY return path_list if __name__ == '__main__': _input = sys.stdin.readlines() vertices_num = int(_input[0]) init_vertices_table = map(lambda x: x.split(), _input[1:]) # assert len(init_vertices_table) == vertices_num parent_list, path_list = [-1] * vertices_num, [D_MAX] * vertices_num color = [WHITE] * vertices_num init_adj_table = tuple(dict() for _ in range(vertices_num)) init_vertex_index = 0 adj_table = generate_adj_table(init_vertices_table) ans = dijkstra_path_heap() for i, v in enumerate(ans): print(i, v) ```
output
1
32,467
13
64,935
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. For a given weighted graph $G = (V, E)$, find the shortest path from a source to each vertex. For each vertex $u$, print the total weight of edges on the shortest path from vertex $0$ to $u$. Constraints * $1 \leq n \leq 10,000$ * $0 \leq c_i \leq 100,000$ * $|E| < 500,000$ * All vertices are reachable from vertex $0$ Input In the first line, an integer $n$ denoting the number of vertices in $G$ is given. In the following $n$ lines, adjacency lists for each vertex $u$ are respectively given in the following format: $u$ $k$ $v_1$ $c_1$ $v_2$ $c_2$ ... $v_k$ $c_k$ Vertices in $G$ are named with IDs $0, 1, ..., n-1$. $u$ is ID of the target vertex and $k$ denotes its degree. $v_i (i = 1, 2, ... k)$ denote IDs of vertices adjacent to $u$ and $c_i$ denotes the weight of a directed edge connecting $u$ and $v_i$ (from $u$ to $v_i$). Output For each vertex, print its ID and the distance separated by a space character in a line respectively. Print in order of vertex IDs. Example Input 5 0 3 2 3 3 1 1 2 1 2 0 2 3 4 2 3 0 3 3 1 4 1 3 4 2 1 0 1 1 4 4 3 4 2 2 1 3 3 Output 0 0 1 2 2 2 3 1 4 3 Submitted Solution: ``` import sys f_i = sys.stdin n = int(f_i.readline()) class VCost: def __init__(self, v, cost): self.v_n = v self.cost = cost def __lt__(self, other): return self.cost < other.cost def __gt__(self, other): return self.cost > other.cost adj = [[VCost(int(v), int(c)) for v, c in zip(x.split()[2::2], x.split()[3::2])] for x in f_i] import heapq def dijkstra(): PQ = [] isVisited = [False] * n distance = [999900001] * n distance[0] = 0 heapq.heappush(PQ, VCost(0, 0)) while PQ: uc = heapq.heappop(PQ) u = uc.v_n if uc.cost > distance[uc.v_n]: continue isVisited[u] = True for vc in adj[u]: v = vc.v_n if isVisited[v] == True: continue t_cost = distance[u] + vc.cost if t_cost < distance[v]: distance[v] = t_cost heapq.heappush(PQ, VCost(v, t_cost)) for v, d in enumerate(distance): print(v, d) dijkstra() ```
instruction
0
32,468
13
64,936
Yes
output
1
32,468
13
64,937
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. For a given weighted graph $G = (V, E)$, find the shortest path from a source to each vertex. For each vertex $u$, print the total weight of edges on the shortest path from vertex $0$ to $u$. Constraints * $1 \leq n \leq 10,000$ * $0 \leq c_i \leq 100,000$ * $|E| < 500,000$ * All vertices are reachable from vertex $0$ Input In the first line, an integer $n$ denoting the number of vertices in $G$ is given. In the following $n$ lines, adjacency lists for each vertex $u$ are respectively given in the following format: $u$ $k$ $v_1$ $c_1$ $v_2$ $c_2$ ... $v_k$ $c_k$ Vertices in $G$ are named with IDs $0, 1, ..., n-1$. $u$ is ID of the target vertex and $k$ denotes its degree. $v_i (i = 1, 2, ... k)$ denote IDs of vertices adjacent to $u$ and $c_i$ denotes the weight of a directed edge connecting $u$ and $v_i$ (from $u$ to $v_i$). Output For each vertex, print its ID and the distance separated by a space character in a line respectively. Print in order of vertex IDs. Example Input 5 0 3 2 3 3 1 1 2 1 2 0 2 3 4 2 3 0 3 3 1 4 1 3 4 2 1 0 1 1 4 4 3 4 2 2 1 3 3 Output 0 0 1 2 2 2 3 1 4 3 Submitted Solution: ``` from heapq import* I=float("inf") def m(): n=int(input()) A=[] for _ in range(n): e=list(map(int,input().split())) A+=[zip(e[2::2],e[3::2])] d=[0]+[I]*n H=[(0,0)] while H: u=heappop(H)[1] for v,c in A[u]: t=d[u]+c if d[v]>t: d[v]=t heappush(H,(t,v)) print('\n'.join(f'{i} {d[i]}'for i in range(n))) m() ```
instruction
0
32,469
13
64,938
Yes
output
1
32,469
13
64,939
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. For a given weighted graph $G = (V, E)$, find the shortest path from a source to each vertex. For each vertex $u$, print the total weight of edges on the shortest path from vertex $0$ to $u$. Constraints * $1 \leq n \leq 10,000$ * $0 \leq c_i \leq 100,000$ * $|E| < 500,000$ * All vertices are reachable from vertex $0$ Input In the first line, an integer $n$ denoting the number of vertices in $G$ is given. In the following $n$ lines, adjacency lists for each vertex $u$ are respectively given in the following format: $u$ $k$ $v_1$ $c_1$ $v_2$ $c_2$ ... $v_k$ $c_k$ Vertices in $G$ are named with IDs $0, 1, ..., n-1$. $u$ is ID of the target vertex and $k$ denotes its degree. $v_i (i = 1, 2, ... k)$ denote IDs of vertices adjacent to $u$ and $c_i$ denotes the weight of a directed edge connecting $u$ and $v_i$ (from $u$ to $v_i$). Output For each vertex, print its ID and the distance separated by a space character in a line respectively. Print in order of vertex IDs. Example Input 5 0 3 2 3 3 1 1 2 1 2 0 2 3 4 2 3 0 3 3 1 4 1 3 4 2 1 0 1 1 4 4 3 4 2 2 1 3 3 Output 0 0 1 2 2 2 3 1 4 3 Submitted Solution: ``` n=int(input()) g=[[]for i in range(n)] for i in range(n): d=list(map(int,input().split())) for j in range(d[1]): g[d[0]].append((d[2+j*2+1],d[2+j*2])) def dijkstra(g,st,ed): from heapq import heappush, heappop, heapify inf=10**18 dist=[inf for i in range(len(g))] visited=[False for i in range(len(g))] dist[st]=0 que=[] heappush(que,(0,st)) while que: c,v=heappop(que) if visited[v]: continue visited[v]=True for x in g[v]: tmp=x[0]+c if tmp<dist[x[1]] and not visited[x[1]]: dist[x[1]]=tmp heappush(que,(tmp,x[1])) return dist dist=dijkstra(g,0,n-1) for i in range(n): print(i,dist[i]) ```
instruction
0
32,470
13
64,940
Yes
output
1
32,470
13
64,941
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. For a given weighted graph $G = (V, E)$, find the shortest path from a source to each vertex. For each vertex $u$, print the total weight of edges on the shortest path from vertex $0$ to $u$. Constraints * $1 \leq n \leq 10,000$ * $0 \leq c_i \leq 100,000$ * $|E| < 500,000$ * All vertices are reachable from vertex $0$ Input In the first line, an integer $n$ denoting the number of vertices in $G$ is given. In the following $n$ lines, adjacency lists for each vertex $u$ are respectively given in the following format: $u$ $k$ $v_1$ $c_1$ $v_2$ $c_2$ ... $v_k$ $c_k$ Vertices in $G$ are named with IDs $0, 1, ..., n-1$. $u$ is ID of the target vertex and $k$ denotes its degree. $v_i (i = 1, 2, ... k)$ denote IDs of vertices adjacent to $u$ and $c_i$ denotes the weight of a directed edge connecting $u$ and $v_i$ (from $u$ to $v_i$). Output For each vertex, print its ID and the distance separated by a space character in a line respectively. Print in order of vertex IDs. Example Input 5 0 3 2 3 3 1 1 2 1 2 0 2 3 4 2 3 0 3 3 1 4 1 3 4 2 1 0 1 1 4 4 3 4 2 2 1 3 3 Output 0 0 1 2 2 2 3 1 4 3 Submitted Solution: ``` import heapq WHITE = 0 GRAY = 1 BLACK = 2 INFTY = 10**13 def dijkstra(s): color = [WHITE for i in range(N)] d = [INFTY for i in range(N)] d[s] = 0 pq = [] heapq.heappush(pq, (0, s)) while len(pq) != 0: u = heapq.heappop(pq)[1] color[u] = BLACK for v, c in VC[u]: if color[v] != BLACK: if d[u] + c < d[v]: d[v] = d[u] + c color[v] = GRAY heapq.heappush(pq, (d[v], v)) return d N = int(input()) VC = [[] for i in range(N)] for i in range(N): ukvc = list(map(int, input().split())) u, k, vc = ukvc[0], ukvc[1], ukvc[2:] for v, c in zip(vc[0::2], vc[1::2]): VC[u].append([v, c]) d = dijkstra(0) for i in range(N): print(i, d[i]) ```
instruction
0
32,471
13
64,942
Yes
output
1
32,471
13
64,943
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. For a given weighted graph $G = (V, E)$, find the shortest path from a source to each vertex. For each vertex $u$, print the total weight of edges on the shortest path from vertex $0$ to $u$. Constraints * $1 \leq n \leq 10,000$ * $0 \leq c_i \leq 100,000$ * $|E| < 500,000$ * All vertices are reachable from vertex $0$ Input In the first line, an integer $n$ denoting the number of vertices in $G$ is given. In the following $n$ lines, adjacency lists for each vertex $u$ are respectively given in the following format: $u$ $k$ $v_1$ $c_1$ $v_2$ $c_2$ ... $v_k$ $c_k$ Vertices in $G$ are named with IDs $0, 1, ..., n-1$. $u$ is ID of the target vertex and $k$ denotes its degree. $v_i (i = 1, 2, ... k)$ denote IDs of vertices adjacent to $u$ and $c_i$ denotes the weight of a directed edge connecting $u$ and $v_i$ (from $u$ to $v_i$). Output For each vertex, print its ID and the distance separated by a space character in a line respectively. Print in order of vertex IDs. Example Input 5 0 3 2 3 3 1 1 2 1 2 0 2 3 4 2 3 0 3 3 1 4 1 3 4 2 1 0 1 1 4 4 3 4 2 2 1 3 3 Output 0 0 1 2 2 2 3 1 4 3 Submitted Solution: ``` import sys def dijkstra(v_count: int, edges: list, start: int, *, adj_matrix: bool = False, unreachable=float("inf")) -> list: """ ダイクストラ法 :param v_count: 頂点数 :param edges: 辺のリスト(隣接リストor隣接行列) :param start: スタートする頂点 :param adj_matrix: edgesに渡したリストが隣接行列ならTrue :param unreachable: 到達不能を表すコスト値 隣接行列の辺の有無の判定および返すリストの初期値に使用 """ from heapq import heappush, heappop vertices = [unreachable] * v_count vertices[start] = 0 q, rem = [(0, start)], v_count - 1 while q and rem: cost, v = heappop(q) if vertices[v] < cost: continue rem -= 1 dests = (filter(lambda x: x[1] != unreachable, enumerate(edges[v])) if adj_matrix else edges[v]) for dest, _cost in dests: newcost = cost + _cost if vertices[dest] > newcost: vertices[dest] = newcost heappush(q, (newcost, dest)) return vertices n = int(input()) inf = float("inf") edges = [[inf]*n for _ in [0]*n] for a in (tuple(map(int, l.split())) for l in sys.stdin): _from = a[0] for to, cost in zip(a[2::2], a[3::2]): edges[_from][to] = cost vertices = dijkstra(n, edges, 0, adj_matrix=True) for i, n in enumerate(vertices): print(i, n) ```
instruction
0
32,472
13
64,944
No
output
1
32,472
13
64,945
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. For a given weighted graph $G = (V, E)$, find the shortest path from a source to each vertex. For each vertex $u$, print the total weight of edges on the shortest path from vertex $0$ to $u$. Constraints * $1 \leq n \leq 10,000$ * $0 \leq c_i \leq 100,000$ * $|E| < 500,000$ * All vertices are reachable from vertex $0$ Input In the first line, an integer $n$ denoting the number of vertices in $G$ is given. In the following $n$ lines, adjacency lists for each vertex $u$ are respectively given in the following format: $u$ $k$ $v_1$ $c_1$ $v_2$ $c_2$ ... $v_k$ $c_k$ Vertices in $G$ are named with IDs $0, 1, ..., n-1$. $u$ is ID of the target vertex and $k$ denotes its degree. $v_i (i = 1, 2, ... k)$ denote IDs of vertices adjacent to $u$ and $c_i$ denotes the weight of a directed edge connecting $u$ and $v_i$ (from $u$ to $v_i$). Output For each vertex, print its ID and the distance separated by a space character in a line respectively. Print in order of vertex IDs. Example Input 5 0 3 2 3 3 1 1 2 1 2 0 2 3 4 2 3 0 3 3 1 4 1 3 4 2 1 0 1 1 4 4 3 4 2 2 1 3 3 Output 0 0 1 2 2 2 3 1 4 3 Submitted Solution: ``` #!/usr/bin/env python # -*- coding: utf-8 -*- """ input: 5 0 3 2 3 3 1 1 2 1 2 0 2 3 4 2 3 0 3 3 1 4 1 3 4 2 1 0 1 1 4 4 3 4 2 2 1 3 3 output: 0 0 1 2 2 2 3 1 4 3 """ import sys import heapq as hp WHITE, GRAY, BLACK = 0, 1, 2 D_MAX = int(5e10 + 1) def generate_adj_matrix(v_info): for each in v_info: v_index, v_adj_length, *v_adj_list = map(int, each) # assert len(v_adj_list) == v_adj_length * 2 for pair in zip(v_adj_list[::2], v_adj_list[1::2]): init_adj_matrix[v_index][pair[0]] = pair[1] return init_adj_matrix def dijkstra_path(): # path search init path_list[init_vertex_index] = 0 path_heap = [] # heapq: rank by tuple[0], here ranked by d[u] hp.heappush(path_heap, (0, init_vertex_index)) while len(path_heap) >= 1: current_vertex_index = hp.heappop(path_heap)[1] color[current_vertex_index] = BLACK current_vertex_index_info = adj_table[current_vertex_index] for adj_vertex_index in current_vertex_index_info.keys(): current_adj_weight = current_vertex_index_info.get(adj_vertex_index) if not current_adj_weight: continue elif color[adj_vertex_index] is not BLACK: # alt: d[u] + w[u,v] alt_path = path_list[current_vertex_index] + current_adj_weight if alt_path < path_list[adj_vertex_index]: # update path_list path_list[adj_vertex_index] = alt_path # update heap hp.heappush(path_heap, (alt_path, adj_vertex_index)) parent_list[adj_vertex_index] = current_vertex_index color[adj_vertex_index] = GRAY return path_list if __name__ == '__main__': _input = sys.stdin.readlines() vertices_num = int(_input[0]) init_vertices_table = map(lambda x: x.split(), _input[1:]) # assert len(init_vertices_table) == vertices_num parent_list, path_list = [-1] * vertices_num, [D_MAX] * vertices_num color = [WHITE] * vertices_num init_adj_matrix = tuple(dict() for _ in range(vertices_num)) init_vertex_index = 0 adj_table = generate_adj_matrix(init_vertices_table) ans = dijkstra_path() for i, v in enumerate(ans): print(i, v) ```
instruction
0
32,473
13
64,946
No
output
1
32,473
13
64,947
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. For a given weighted graph $G = (V, E)$, find the shortest path from a source to each vertex. For each vertex $u$, print the total weight of edges on the shortest path from vertex $0$ to $u$. Constraints * $1 \leq n \leq 10,000$ * $0 \leq c_i \leq 100,000$ * $|E| < 500,000$ * All vertices are reachable from vertex $0$ Input In the first line, an integer $n$ denoting the number of vertices in $G$ is given. In the following $n$ lines, adjacency lists for each vertex $u$ are respectively given in the following format: $u$ $k$ $v_1$ $c_1$ $v_2$ $c_2$ ... $v_k$ $c_k$ Vertices in $G$ are named with IDs $0, 1, ..., n-1$. $u$ is ID of the target vertex and $k$ denotes its degree. $v_i (i = 1, 2, ... k)$ denote IDs of vertices adjacent to $u$ and $c_i$ denotes the weight of a directed edge connecting $u$ and $v_i$ (from $u$ to $v_i$). Output For each vertex, print its ID and the distance separated by a space character in a line respectively. Print in order of vertex IDs. Example Input 5 0 3 2 3 3 1 1 2 1 2 0 2 3 4 2 3 0 3 3 1 4 1 3 4 2 1 0 1 1 4 4 3 4 2 2 1 3 3 Output 0 0 1 2 2 2 3 1 4 3 Submitted Solution: ``` #!/usr/bin/env python # -*- coding: utf-8 -*- """ input: 5 0 3 2 3 3 1 1 2 1 2 0 2 3 4 2 3 0 3 3 1 4 1 3 4 2 1 0 1 1 4 4 3 4 2 2 1 3 3 output: 0 0 1 2 2 2 3 1 4 3 """ import sys WHITE, GRAY, BLACK = 0, 1, 2 D_MAX = int(1e7 + 1) def generate_adj_matrix(v_info): for v_detail in v_info: v_index = int(v_detail[0]) v_adj_length = int(v_detail[1]) v_adj_list = v_detail[2:] # assert len(v_adj_list) == v_adj_length * 2 for j in range(0, v_adj_length * 2, 2): init_adj_matrix[v_index][v_adj_list[j]] = int(v_adj_list[j + 1]) return init_adj_matrix def dijkstra_path(): path_list[0] = 0 while True: min_cost = D_MAX current_vertex = None for i in range(vertices_num): if color[i] is not BLACK and path_list[i] < min_cost: min_cost = path_list[i] current_vertex = i if min_cost == D_MAX: break color[current_vertex] = BLACK for adj_vertex in range(vertices_num): current_adj_weight = adj_matrix[current_vertex].get(str(adj_vertex), -1) if current_adj_weight < 0: continue elif color[adj_vertex] is not BLACK: if path_list[current_vertex] + current_adj_weight < path_list[adj_vertex]: path_list[adj_vertex] = path_list[current_vertex] + current_adj_weight parent_list[adj_vertex] = current_vertex color[adj_vertex] = GRAY return path_list if __name__ == '__main__': _input = sys.stdin.readlines() vertices_num = int(_input[0]) init_vertices_table = list(map(lambda x: x.split(), _input[1:])) # assert len(init_vertices_table) == vertices_num parent_list, path_list = [-1] * vertices_num, [D_MAX] * vertices_num color = [WHITE] * vertices_num init_adj_matrix = tuple(dict() for _ in range(vertices_num)) adj_matrix = generate_adj_matrix(init_vertices_table) ans = dijkstra_path() for j in range(vertices_num): print(j, ans[j]) ```
instruction
0
32,474
13
64,948
No
output
1
32,474
13
64,949
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. For a given weighted graph $G = (V, E)$, find the shortest path from a source to each vertex. For each vertex $u$, print the total weight of edges on the shortest path from vertex $0$ to $u$. Constraints * $1 \leq n \leq 10,000$ * $0 \leq c_i \leq 100,000$ * $|E| < 500,000$ * All vertices are reachable from vertex $0$ Input In the first line, an integer $n$ denoting the number of vertices in $G$ is given. In the following $n$ lines, adjacency lists for each vertex $u$ are respectively given in the following format: $u$ $k$ $v_1$ $c_1$ $v_2$ $c_2$ ... $v_k$ $c_k$ Vertices in $G$ are named with IDs $0, 1, ..., n-1$. $u$ is ID of the target vertex and $k$ denotes its degree. $v_i (i = 1, 2, ... k)$ denote IDs of vertices adjacent to $u$ and $c_i$ denotes the weight of a directed edge connecting $u$ and $v_i$ (from $u$ to $v_i$). Output For each vertex, print its ID and the distance separated by a space character in a line respectively. Print in order of vertex IDs. Example Input 5 0 3 2 3 3 1 1 2 1 2 0 2 3 4 2 3 0 3 3 1 4 1 3 4 2 1 0 1 1 4 4 3 4 2 2 1 3 3 Output 0 0 1 2 2 2 3 1 4 3 Submitted Solution: ``` # -*- coding: utf-8 -*- from heapq import heappop, heappush N = int(input()) INF = 1 << 12 adj = [[] for _ in range(N)] for n in range(N): inp = tuple(map(int, input().split())) adj[n] = list(zip(inp[2::2], inp[3::2])) def dijkstra(): d = [INF for n in range(N)] d[0] = 0 heap = [[0, 0]] while len(heap): pcost, p = heappop(heap) for v, c in adj[p]: new_cost = d[p] + c if new_cost < d[v]: d[v] = new_cost heappush(heap, [new_cost, v]) for n in range(N): print("{} {}".format(n, d[n])) dijkstra() ```
instruction
0
32,475
13
64,950
No
output
1
32,475
13
64,951
Provide tags and a correct Python 3 solution for this coding contest problem. You're given an undirected graph with n nodes and m edges. Nodes are numbered from 1 to n. The graph is considered harmonious if and only if the following property holds: * For every triple of integers (l, m, r) such that 1 ≤ l < m < r ≤ n, if there exists a path going from node l to node r, then there exists a path going from node l to node m. In other words, in a harmonious graph, if from a node l we can reach a node r through edges (l < r), then we should able to reach nodes (l+1), (l+2), …, (r-1) too. What is the minimum number of edges we need to add to make the graph harmonious? Input The first line contains two integers n and m (3 ≤ n ≤ 200\ 000 and 1 ≤ m ≤ 200\ 000). The i-th of the next m lines contains two integers u_i and v_i (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i), that mean that there's an edge between nodes u and v. It is guaranteed that the given graph is simple (there is no self-loop, and there is at most one edge between every pair of nodes). Output Print the minimum number of edges we have to add to the graph to make it harmonious. Examples Input 14 8 1 2 2 7 3 4 6 3 5 7 3 8 6 8 11 12 Output 1 Input 200000 3 7 9 9 8 4 5 Output 0 Note In the first example, the given graph is not harmonious (for instance, 1 < 6 < 7, node 1 can reach node 7 through the path 1 → 2 → 7, but node 1 can't reach node 6). However adding the edge (2, 4) is sufficient to make it harmonious. In the second example, the given graph is already harmonious.
instruction
0
32,634
13
65,268
Tags: constructive algorithms, dfs and similar, dsu, graphs, greedy, sortings Correct Solution: ``` # unionfind class Uf: def __init__(self, N): self.p = list(range(N)) self.rank = [0] * N self.size = [1] * N def root(self, x): if self.p[x] != x: self.p[x] = self.root(self.p[x]) return self.p[x] def same(self, x, y): return self.root(x) == self.root(y) def unite(self, x, y): u = self.root(x) v = self.root(y) if u == v: return if self.rank[u] < self.rank[v]: self.p[u] = v self.size[v] += self.size[u] self.size[u] = 0 else: self.p[v] = u self.size[u] += self.size[v] self.size[v] = 0 if self.rank[u] == self.rank[v]: self.rank[u] += 1 def count(self, x): return self.size[self.root(x)] import sys from operator import itemgetter def main(): input = sys.stdin.readline N, M = map(int, input().split()) # harmonious <=> l < m < r で、l から r に辿り着けるなら、l から m に辿り着ける uf = Uf(N+1) for u, v in zip(*[iter(map(int, sys.stdin.read().split()))]*2): uf.unite(u, v) L = [10**9] * (N+1) R = [-1] * (N+1) for i in range(1, N+1): r = uf.root(i) L[r] = min(L[r], i) R[r] = max(R[r], i) ans = 0 LR = [] for l, r in zip(L, R): if r != -1: LR.append((l, r)) LR.sort(key=itemgetter(0)) rr = -1 for l, r in LR: if rr > l: ans += 1 rr = max(rr, r) print(ans) main() ```
output
1
32,634
13
65,269
Provide tags and a correct Python 3 solution for this coding contest problem. You're given an undirected graph with n nodes and m edges. Nodes are numbered from 1 to n. The graph is considered harmonious if and only if the following property holds: * For every triple of integers (l, m, r) such that 1 ≤ l < m < r ≤ n, if there exists a path going from node l to node r, then there exists a path going from node l to node m. In other words, in a harmonious graph, if from a node l we can reach a node r through edges (l < r), then we should able to reach nodes (l+1), (l+2), …, (r-1) too. What is the minimum number of edges we need to add to make the graph harmonious? Input The first line contains two integers n and m (3 ≤ n ≤ 200\ 000 and 1 ≤ m ≤ 200\ 000). The i-th of the next m lines contains two integers u_i and v_i (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i), that mean that there's an edge between nodes u and v. It is guaranteed that the given graph is simple (there is no self-loop, and there is at most one edge between every pair of nodes). Output Print the minimum number of edges we have to add to the graph to make it harmonious. Examples Input 14 8 1 2 2 7 3 4 6 3 5 7 3 8 6 8 11 12 Output 1 Input 200000 3 7 9 9 8 4 5 Output 0 Note In the first example, the given graph is not harmonious (for instance, 1 < 6 < 7, node 1 can reach node 7 through the path 1 → 2 → 7, but node 1 can't reach node 6). However adding the edge (2, 4) is sufficient to make it harmonious. In the second example, the given graph is already harmonious.
instruction
0
32,635
13
65,270
Tags: constructive algorithms, dfs and similar, dsu, graphs, greedy, sortings Correct Solution: ``` import io, os input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline n, m = [int(s) for s in input().split()] parent = [i for i in range(n + 1)] def find(a): a1 = a while a != parent[a]: a = parent[a] parent[a1] = a return a for i in range(m): u, v = [int(s) for s in input().split()] pv = find(v) pu = find(u) if pu < pv: pu, pv = pv, pu parent[pv] = pu for i in range(n, 0, -1): parent[i] = find(i) ans = 0 bar = 0 for i in range(n): bar = max(bar, parent[i]) if parent[i] == i: if bar == i: bar = i + 1 else: ans += 1 print(ans) ```
output
1
32,635
13
65,271
Provide tags and a correct Python 3 solution for this coding contest problem. You're given an undirected graph with n nodes and m edges. Nodes are numbered from 1 to n. The graph is considered harmonious if and only if the following property holds: * For every triple of integers (l, m, r) such that 1 ≤ l < m < r ≤ n, if there exists a path going from node l to node r, then there exists a path going from node l to node m. In other words, in a harmonious graph, if from a node l we can reach a node r through edges (l < r), then we should able to reach nodes (l+1), (l+2), …, (r-1) too. What is the minimum number of edges we need to add to make the graph harmonious? Input The first line contains two integers n and m (3 ≤ n ≤ 200\ 000 and 1 ≤ m ≤ 200\ 000). The i-th of the next m lines contains two integers u_i and v_i (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i), that mean that there's an edge between nodes u and v. It is guaranteed that the given graph is simple (there is no self-loop, and there is at most one edge between every pair of nodes). Output Print the minimum number of edges we have to add to the graph to make it harmonious. Examples Input 14 8 1 2 2 7 3 4 6 3 5 7 3 8 6 8 11 12 Output 1 Input 200000 3 7 9 9 8 4 5 Output 0 Note In the first example, the given graph is not harmonious (for instance, 1 < 6 < 7, node 1 can reach node 7 through the path 1 → 2 → 7, but node 1 can't reach node 6). However adding the edge (2, 4) is sufficient to make it harmonious. In the second example, the given graph is already harmonious.
instruction
0
32,636
13
65,272
Tags: constructive algorithms, dfs and similar, dsu, graphs, greedy, sortings Correct Solution: ``` from collections import defaultdict import threading, sys sys.setrecursionlimit(10**8) visited = [False] * 200010 graph = defaultdict(set) def read(): return sys.stdin.readline().split() def dfs(start): visited[start] = True ret = start for v in graph[start]: if not visited[v]: ret = max(dfs(v), ret) return ret def main(): n, m = map(int, read()) for _ in range(m): u, v = map(int, read()) u, v = u-1, v-1 graph[u].add(v) graph[v].add(u) max_r = 0 ans = 0 for l in range(n): if not visited[l]: r = dfs(l) if l < max_r: ans += 1 max_r = max(r,max_r) print(ans) if __name__ == "__main__": threading.stack_size(1024 * 100000) thread = threading.Thread(target=main) thread.start() thread.join() ```
output
1
32,636
13
65,273
Provide tags and a correct Python 3 solution for this coding contest problem. You're given an undirected graph with n nodes and m edges. Nodes are numbered from 1 to n. The graph is considered harmonious if and only if the following property holds: * For every triple of integers (l, m, r) such that 1 ≤ l < m < r ≤ n, if there exists a path going from node l to node r, then there exists a path going from node l to node m. In other words, in a harmonious graph, if from a node l we can reach a node r through edges (l < r), then we should able to reach nodes (l+1), (l+2), …, (r-1) too. What is the minimum number of edges we need to add to make the graph harmonious? Input The first line contains two integers n and m (3 ≤ n ≤ 200\ 000 and 1 ≤ m ≤ 200\ 000). The i-th of the next m lines contains two integers u_i and v_i (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i), that mean that there's an edge between nodes u and v. It is guaranteed that the given graph is simple (there is no self-loop, and there is at most one edge between every pair of nodes). Output Print the minimum number of edges we have to add to the graph to make it harmonious. Examples Input 14 8 1 2 2 7 3 4 6 3 5 7 3 8 6 8 11 12 Output 1 Input 200000 3 7 9 9 8 4 5 Output 0 Note In the first example, the given graph is not harmonious (for instance, 1 < 6 < 7, node 1 can reach node 7 through the path 1 → 2 → 7, but node 1 can't reach node 6). However adding the edge (2, 4) is sufficient to make it harmonious. In the second example, the given graph is already harmonious.
instruction
0
32,637
13
65,274
Tags: constructive algorithms, dfs and similar, dsu, graphs, greedy, sortings Correct Solution: ``` from bisect import bisect_left as bl, bisect_right as br, insort import sys import heapq # from math import * from collections import defaultdict as dd, deque def data(): return sys.stdin.readline().strip() def mdata(): return map(int, data().split()) #sys.setrecursionlimit(1000000) mod = int(1e9 + 7) n,m=mdata() Group = [i for i in range(n + 1)] Nodes = [1] * (n + 1) def find(x): while Group[x] != x: x = Group[x] return x def Union(x, y): if find(x) != find(y): if Nodes[find(x)] < Nodes[find(y)]: Nodes[find(y)] += Nodes[find(x)] Nodes[find(x)] = 0 Group[find(x)] = find(y) else: Nodes[find(x)] += Nodes[find(y)] Nodes[find(y)] = 0 Group[find(y)] = find(x) for i in range(m): x, y = mdata() Union(x, y) d=dd(int) for i in range(1,n+1): d[find(i)]=i ans=0 m=1 for i in range(1,n+1): if m>d[find(i)]: d[find(i)]=m Union(m,i) ans+=1 else: m=d[find(i)] print(ans) ```
output
1
32,637
13
65,275
Provide tags and a correct Python 3 solution for this coding contest problem. You're given an undirected graph with n nodes and m edges. Nodes are numbered from 1 to n. The graph is considered harmonious if and only if the following property holds: * For every triple of integers (l, m, r) such that 1 ≤ l < m < r ≤ n, if there exists a path going from node l to node r, then there exists a path going from node l to node m. In other words, in a harmonious graph, if from a node l we can reach a node r through edges (l < r), then we should able to reach nodes (l+1), (l+2), …, (r-1) too. What is the minimum number of edges we need to add to make the graph harmonious? Input The first line contains two integers n and m (3 ≤ n ≤ 200\ 000 and 1 ≤ m ≤ 200\ 000). The i-th of the next m lines contains two integers u_i and v_i (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i), that mean that there's an edge between nodes u and v. It is guaranteed that the given graph is simple (there is no self-loop, and there is at most one edge between every pair of nodes). Output Print the minimum number of edges we have to add to the graph to make it harmonious. Examples Input 14 8 1 2 2 7 3 4 6 3 5 7 3 8 6 8 11 12 Output 1 Input 200000 3 7 9 9 8 4 5 Output 0 Note In the first example, the given graph is not harmonious (for instance, 1 < 6 < 7, node 1 can reach node 7 through the path 1 → 2 → 7, but node 1 can't reach node 6). However adding the edge (2, 4) is sufficient to make it harmonious. In the second example, the given graph is already harmonious.
instruction
0
32,638
13
65,276
Tags: constructive algorithms, dfs and similar, dsu, graphs, greedy, sortings Correct Solution: ``` import sys input = sys.stdin.readline n,m=map(int,input().split()) #E=[tuple(map(int,input().split())) for i in range(m)] Group=[i for i in range(n+1)] Nodes=[1]*(n+1) def find(x): while Group[x] != x: x=Group[x] return x def Union(x,y): if find(x) != find(y): if Nodes[find(x)]<Nodes[find(y)]: Nodes[find(y)]+=Nodes[find(x)] Nodes[find(x)]=0 Group[find(x)]=find(y) else: Nodes[find(x)]+=Nodes[find(y)] Nodes[find(y)]=0 Group[find(y)]=find(x) for i in range(m): x,y=map(int,input().split()) Union(x,y) MINI=[i for i in range(n+1)] for i in range(n+1): MINI[find(i)]=min(MINI[find(i)],i) ANS=0 MIN=n ANS=0 for i in range(n,0,-1): if MIN<MINI[find(i)]: MINI[find(i)]=min(MINI[find(i)],MINI[find(MIN)]) Union(MIN,i) ANS+=1 else: MIN=MINI[find(i)] #print(i,ANS) print(ANS) ```
output
1
32,638
13
65,277