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. T is a complete binary tree consisting of n vertices. It means that exactly one vertex is a root, and each vertex is either a leaf (and doesn't have children) or an inner node (and has exactly two children). All leaves of a complete binary tree have the same depth (distance from the root). So n is a number such that n + 1 is a power of 2. In the picture you can see a complete binary tree with n = 15. <image> Vertices are numbered from 1 to n in a special recursive way: we recursively assign numbers to all vertices from the left subtree (if current vertex is not a leaf), then assign a number to the current vertex, and then recursively assign numbers to all vertices from the right subtree (if it exists). In the picture vertices are numbered exactly using this algorithm. It is clear that for each size of a complete binary tree exists exactly one way to give numbers to all vertices. This way of numbering is called symmetric. You have to write a program that for given n answers q queries to the tree. Each query consists of an integer number ui (1 ≤ ui ≤ n) and a string si, where ui is the number of vertex, and si represents the path starting from this vertex. String si doesn't contain any characters other than 'L', 'R' and 'U', which mean traverse to the left child, to the right child and to the parent, respectively. Characters from si have to be processed from left to right, considering that ui is the vertex where the path starts. If it's impossible to process a character (for example, to go to the left child of a leaf), then you have to skip it. The answer is the number of vertex where the path represented by si ends. For example, if ui = 4 and si = «UURL», then the answer is 10. Input The first line contains two integer numbers n and q (1 ≤ n ≤ 1018, q ≥ 1). n is such that n + 1 is a power of 2. The next 2q lines represent queries; each query consists of two consecutive lines. The first of these two lines contains ui (1 ≤ ui ≤ n), the second contains non-empty string si. si doesn't contain any characters other than 'L', 'R' and 'U'. It is guaranteed that the sum of lengths of si (for each i such that 1 ≤ i ≤ q) doesn't exceed 105. Output Print q numbers, i-th number must be the answer to the i-th query. Example Input 15 2 4 UURL 8 LRLLLLLLLL Output 10 5 Submitted Solution: ``` import sys input = sys.stdin.readline n, q = map(int, input().split()) for _ in range(q): u = int(input()) s = input() for comm in s: k = 1 while True: if k & u: break k <<= 1 if comm == 'L': if k != 1: u -= k u += (k>>1) elif comm == 'R': if k != 1: u += (k>>1) elif comm == 'U': nu = u - k nu |= (k<<1) if nu <= n: u = nu print(u) ```
instruction
0
52,733
13
105,466
Yes
output
1
52,733
13
105,467
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. T is a complete binary tree consisting of n vertices. It means that exactly one vertex is a root, and each vertex is either a leaf (and doesn't have children) or an inner node (and has exactly two children). All leaves of a complete binary tree have the same depth (distance from the root). So n is a number such that n + 1 is a power of 2. In the picture you can see a complete binary tree with n = 15. <image> Vertices are numbered from 1 to n in a special recursive way: we recursively assign numbers to all vertices from the left subtree (if current vertex is not a leaf), then assign a number to the current vertex, and then recursively assign numbers to all vertices from the right subtree (if it exists). In the picture vertices are numbered exactly using this algorithm. It is clear that for each size of a complete binary tree exists exactly one way to give numbers to all vertices. This way of numbering is called symmetric. You have to write a program that for given n answers q queries to the tree. Each query consists of an integer number ui (1 ≤ ui ≤ n) and a string si, where ui is the number of vertex, and si represents the path starting from this vertex. String si doesn't contain any characters other than 'L', 'R' and 'U', which mean traverse to the left child, to the right child and to the parent, respectively. Characters from si have to be processed from left to right, considering that ui is the vertex where the path starts. If it's impossible to process a character (for example, to go to the left child of a leaf), then you have to skip it. The answer is the number of vertex where the path represented by si ends. For example, if ui = 4 and si = «UURL», then the answer is 10. Input The first line contains two integer numbers n and q (1 ≤ n ≤ 1018, q ≥ 1). n is such that n + 1 is a power of 2. The next 2q lines represent queries; each query consists of two consecutive lines. The first of these two lines contains ui (1 ≤ ui ≤ n), the second contains non-empty string si. si doesn't contain any characters other than 'L', 'R' and 'U'. It is guaranteed that the sum of lengths of si (for each i such that 1 ≤ i ≤ q) doesn't exceed 105. Output Print q numbers, i-th number must be the answer to the i-th query. Example Input 15 2 4 UURL 8 LRLLLLLLLL Output 10 5 Submitted Solution: ``` import math p2 =[1] * 64 for i in range(1, 64): p2[i] = p2[i-1] * 2 def find_level(x): x0 = 1 for i in range(max_level+1): if (x-x0) % (x0*2) == 0: return i x0 *=2 def move_U(number): cur_lv = find_level(number) if cur_lv == max_level: return number x0 = p2[cur_lv] seg = x0 * 2 index = (number - x0) // seg return (x0*2) + (index // 2) * (seg * 2) def move_L(number): cur_lv = find_level(number) if cur_lv == 0: return number x0 = p2[cur_lv] seg = x0 * 2 index = (number - x0) // seg return (x0 // 2) + (index * 2) * (seg // 2) def move_R(number): cur_lv = find_level(number) if cur_lv == 0: return number x0 = p2[cur_lv] seg = x0 * 2 index = (number - x0) // seg return (x0 // 2) + (index * 2 + 1) * (seg // 2) def move(s,num): if s == 'U': return move_U(num) if s == 'L': return move_L(num) return move_R(num) def process(S, num): for s in S: num = move(s, num) return num n, q = map(int, input().split()) max_level = int(math.log2(n+1)) - 1 ans = '' for _ in range(q): num = int(input()) S = input() ans += str(process(S, num)) + '\n' print(ans) #15 2 #4 #UURL #8 #LRLLLLLLLL ```
instruction
0
52,734
13
105,468
Yes
output
1
52,734
13
105,469
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. T is a complete binary tree consisting of n vertices. It means that exactly one vertex is a root, and each vertex is either a leaf (and doesn't have children) or an inner node (and has exactly two children). All leaves of a complete binary tree have the same depth (distance from the root). So n is a number such that n + 1 is a power of 2. In the picture you can see a complete binary tree with n = 15. <image> Vertices are numbered from 1 to n in a special recursive way: we recursively assign numbers to all vertices from the left subtree (if current vertex is not a leaf), then assign a number to the current vertex, and then recursively assign numbers to all vertices from the right subtree (if it exists). In the picture vertices are numbered exactly using this algorithm. It is clear that for each size of a complete binary tree exists exactly one way to give numbers to all vertices. This way of numbering is called symmetric. You have to write a program that for given n answers q queries to the tree. Each query consists of an integer number ui (1 ≤ ui ≤ n) and a string si, where ui is the number of vertex, and si represents the path starting from this vertex. String si doesn't contain any characters other than 'L', 'R' and 'U', which mean traverse to the left child, to the right child and to the parent, respectively. Characters from si have to be processed from left to right, considering that ui is the vertex where the path starts. If it's impossible to process a character (for example, to go to the left child of a leaf), then you have to skip it. The answer is the number of vertex where the path represented by si ends. For example, if ui = 4 and si = «UURL», then the answer is 10. Input The first line contains two integer numbers n and q (1 ≤ n ≤ 1018, q ≥ 1). n is such that n + 1 is a power of 2. The next 2q lines represent queries; each query consists of two consecutive lines. The first of these two lines contains ui (1 ≤ ui ≤ n), the second contains non-empty string si. si doesn't contain any characters other than 'L', 'R' and 'U'. It is guaranteed that the sum of lengths of si (for each i such that 1 ≤ i ≤ q) doesn't exceed 105. Output Print q numbers, i-th number must be the answer to the i-th query. Example Input 15 2 4 UURL 8 LRLLLLLLLL Output 10 5 Submitted Solution: ``` ##D. Paths in a Complete Binary Tree ##time limit per test3 seconds ##memory limit per test256 megabytes ##inputstandard input ##outputstandard output ##T is a complete binary tree consisting of n vertices. It means that exactly ##one vertex is a root, and each vertex is either a leaf (and doesn't have ##children) or an inner node (and has exactly two children). All leaves of ##a complete binary tree have the same depth (distance from the root). So n ##is a number such that n + 1 is a power of 2. ## ##In the picture you can see a complete binary tree with n = 15. ## ## ##Vertices are numbered from 1 to n in a special recursive way: we recursively ##assign numbers to all vertices from the left subtree (if current vertex is ##not a leaf), then assign a number to the current vertex, and then ##recursively assign numbers to all vertices from the right subtree (if it exists). In the picture vertices are numbered exactly using this algorithm. It is clear that for each size of a complete binary tree exists exactly one way to give numbers to all vertices. This way of numbering is called symmetric. ## ##You have to write a program that for given n answers q queries to the tree. ## ##Each query consists of an integer number ui (1 ≤ ui ≤ n) and a string si, ##where ui is the number of vertex, and si represents the path starting from this ##vertex. String si doesn't contain any characters other than 'L', 'R' and 'U', ##which mean traverse to the left child, to the right child and to the parent, ##respectively. Characters from si have to be processed from left to right, ##considering that ui is the vertex where the path starts. If it's impossible ##to process a character (for example, to go to the left child of a leaf), then ##you have to skip it. The answer is the number of vertex where the path ##represented by si ends. ## ##For example, if ui = 4 and si = «UURL», then the answer is 10. ## ##Input ##The first line contains two integer numbers n and q (1 ≤ n ≤ 1018, q ≥ 1). n is ##such that n + 1 is a power of 2. ## ##The next 2q lines represent queries; each query consists of two consecutive lines. ##The first of these two lines contains ui (1 ≤ ui ≤ n), the second contains ##non-empty string si. si doesn't contain any characters other than 'L', 'R' and ##'U'. ## ##It is guaranteed that the sum of lengths of si (for each i such that 1 ≤ i ≤ q) ##doesn't exceed 105. ## ##Output ##Print q numbers, i-th number must be the answer to the i-th query. ## ##Example ##input ##15 2 ##4 ##UURL ##8 ##LRLLLLLLLL ##output ##10 ##5 def findTwo(n): x = 0 while( n%2 == 0 ): n /= 2 x += 1 return x def nextNumber (k, n, o): n1 = findTwo(k) k1 = ( k /(2**n1)-1 ) / 2 if( o == "L"): if( n1 > 0): return k - (2 **(n1-1) ) else: return k elif ( o == "R"): if( n1 > 0): return k + ( 2**(n1-1) ) else: return k else: if( n1 == n ): return k elif ( k1 %2 == 0): return k + ( 2**n1 ) elif ( k1 %2 == 1): return k - ( 2**n1 ) n, k = map(int, input().split()) n = findTwo(n + 1) n -= 1 t = [0] * k d = [""] * k for i in range(k): t[i] = int(input()) d[i] = input() for i in range(k): for j in range(len(d[i])): t[i] = nextNumber(t[i], n, d[i][j] ) print(t[i]) ```
instruction
0
52,735
13
105,470
No
output
1
52,735
13
105,471
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. T is a complete binary tree consisting of n vertices. It means that exactly one vertex is a root, and each vertex is either a leaf (and doesn't have children) or an inner node (and has exactly two children). All leaves of a complete binary tree have the same depth (distance from the root). So n is a number such that n + 1 is a power of 2. In the picture you can see a complete binary tree with n = 15. <image> Vertices are numbered from 1 to n in a special recursive way: we recursively assign numbers to all vertices from the left subtree (if current vertex is not a leaf), then assign a number to the current vertex, and then recursively assign numbers to all vertices from the right subtree (if it exists). In the picture vertices are numbered exactly using this algorithm. It is clear that for each size of a complete binary tree exists exactly one way to give numbers to all vertices. This way of numbering is called symmetric. You have to write a program that for given n answers q queries to the tree. Each query consists of an integer number ui (1 ≤ ui ≤ n) and a string si, where ui is the number of vertex, and si represents the path starting from this vertex. String si doesn't contain any characters other than 'L', 'R' and 'U', which mean traverse to the left child, to the right child and to the parent, respectively. Characters from si have to be processed from left to right, considering that ui is the vertex where the path starts. If it's impossible to process a character (for example, to go to the left child of a leaf), then you have to skip it. The answer is the number of vertex where the path represented by si ends. For example, if ui = 4 and si = «UURL», then the answer is 10. Input The first line contains two integer numbers n and q (1 ≤ n ≤ 1018, q ≥ 1). n is such that n + 1 is a power of 2. The next 2q lines represent queries; each query consists of two consecutive lines. The first of these two lines contains ui (1 ≤ ui ≤ n), the second contains non-empty string si. si doesn't contain any characters other than 'L', 'R' and 'U'. It is guaranteed that the sum of lengths of si (for each i such that 1 ≤ i ≤ q) doesn't exceed 105. Output Print q numbers, i-th number must be the answer to the i-th query. Example Input 15 2 4 UURL 8 LRLLLLLLLL Output 10 5 Submitted Solution: ``` def level(v): ans = 1 while v % 2 == 0 and v > 1: v //= 2 ans += 1 return ans def left(v): x = level(v) f = v while f % 2 == 0 and f > 1: f //= 2 if f % (2 ** (x + 1)) == 1: return True return False n, q = map(int, input().split()) for _ in range(q): m = input() s = input() st = (n + 1) // 2 for sym in s: if sym == 'U': if st == (n + 1) // 2: pass else: if left(st): st += 2 ** (level(st) - 1) else: st -= 2 ** (level(st) - 1) elif sym == 'L' and level(st) != 1: st -= 2 ** (level(st) - 2) elif level(st) != 1: st += 2 ** (level(st) - 2) print(st) ```
instruction
0
52,736
13
105,472
No
output
1
52,736
13
105,473
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. T is a complete binary tree consisting of n vertices. It means that exactly one vertex is a root, and each vertex is either a leaf (and doesn't have children) or an inner node (and has exactly two children). All leaves of a complete binary tree have the same depth (distance from the root). So n is a number such that n + 1 is a power of 2. In the picture you can see a complete binary tree with n = 15. <image> Vertices are numbered from 1 to n in a special recursive way: we recursively assign numbers to all vertices from the left subtree (if current vertex is not a leaf), then assign a number to the current vertex, and then recursively assign numbers to all vertices from the right subtree (if it exists). In the picture vertices are numbered exactly using this algorithm. It is clear that for each size of a complete binary tree exists exactly one way to give numbers to all vertices. This way of numbering is called symmetric. You have to write a program that for given n answers q queries to the tree. Each query consists of an integer number ui (1 ≤ ui ≤ n) and a string si, where ui is the number of vertex, and si represents the path starting from this vertex. String si doesn't contain any characters other than 'L', 'R' and 'U', which mean traverse to the left child, to the right child and to the parent, respectively. Characters from si have to be processed from left to right, considering that ui is the vertex where the path starts. If it's impossible to process a character (for example, to go to the left child of a leaf), then you have to skip it. The answer is the number of vertex where the path represented by si ends. For example, if ui = 4 and si = «UURL», then the answer is 10. Input The first line contains two integer numbers n and q (1 ≤ n ≤ 1018, q ≥ 1). n is such that n + 1 is a power of 2. The next 2q lines represent queries; each query consists of two consecutive lines. The first of these two lines contains ui (1 ≤ ui ≤ n), the second contains non-empty string si. si doesn't contain any characters other than 'L', 'R' and 'U'. It is guaranteed that the sum of lengths of si (for each i such that 1 ≤ i ≤ q) doesn't exceed 105. Output Print q numbers, i-th number must be the answer to the i-th query. Example Input 15 2 4 UURL 8 LRLLLLLLLL Output 10 5 Submitted Solution: ``` #include ```
instruction
0
52,737
13
105,474
No
output
1
52,737
13
105,475
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. T is a complete binary tree consisting of n vertices. It means that exactly one vertex is a root, and each vertex is either a leaf (and doesn't have children) or an inner node (and has exactly two children). All leaves of a complete binary tree have the same depth (distance from the root). So n is a number such that n + 1 is a power of 2. In the picture you can see a complete binary tree with n = 15. <image> Vertices are numbered from 1 to n in a special recursive way: we recursively assign numbers to all vertices from the left subtree (if current vertex is not a leaf), then assign a number to the current vertex, and then recursively assign numbers to all vertices from the right subtree (if it exists). In the picture vertices are numbered exactly using this algorithm. It is clear that for each size of a complete binary tree exists exactly one way to give numbers to all vertices. This way of numbering is called symmetric. You have to write a program that for given n answers q queries to the tree. Each query consists of an integer number ui (1 ≤ ui ≤ n) and a string si, where ui is the number of vertex, and si represents the path starting from this vertex. String si doesn't contain any characters other than 'L', 'R' and 'U', which mean traverse to the left child, to the right child and to the parent, respectively. Characters from si have to be processed from left to right, considering that ui is the vertex where the path starts. If it's impossible to process a character (for example, to go to the left child of a leaf), then you have to skip it. The answer is the number of vertex where the path represented by si ends. For example, if ui = 4 and si = «UURL», then the answer is 10. Input The first line contains two integer numbers n and q (1 ≤ n ≤ 1018, q ≥ 1). n is such that n + 1 is a power of 2. The next 2q lines represent queries; each query consists of two consecutive lines. The first of these two lines contains ui (1 ≤ ui ≤ n), the second contains non-empty string si. si doesn't contain any characters other than 'L', 'R' and 'U'. It is guaranteed that the sum of lengths of si (for each i such that 1 ≤ i ≤ q) doesn't exceed 105. Output Print q numbers, i-th number must be the answer to the i-th query. Example Input 15 2 4 UURL 8 LRLLLLLLLL Output 10 5 Submitted Solution: ``` import sys n, q = map(int, input().split()) top = len(bin(n >> 1)) - 2 ans = [0] * q for i in range(q): m = int(input()) s = input() h, v = top, 1 << top for c in s: if h == top and c == 'U' or h == 0 and c != 'U': continue if c == 'U': v -= 1 << h h += 1 v |= 1 << h elif c == 'L': v -= 1 << h h -= 1 v |= 1 << h else: h -= 1 v |= 1 << h ans[i] = v print(*ans, sep='\n') ```
instruction
0
52,738
13
105,476
No
output
1
52,738
13
105,477
Provide tags and a correct Python 3 solution for this coding contest problem. The main characters have been omitted to be short. You are given a directed unweighted graph without loops with n vertexes and a path in it (that path is not necessary simple) given by a sequence p_1, p_2, …, p_m of m vertexes; for each 1 ≤ i < m there is an arc from p_i to p_{i+1}. Define the sequence v_1, v_2, …, v_k of k vertexes as good, if v is a subsequence of p, v_1 = p_1, v_k = p_m, and p is one of the shortest paths passing through the vertexes v_1, …, v_k in that order. A sequence a is a subsequence of a sequence b if a can be obtained from b by deletion of several (possibly, zero or all) elements. It is obvious that the sequence p is good but your task is to find the shortest good subsequence. If there are multiple shortest good subsequences, output any of them. Input The first line contains a single integer n (2 ≤ n ≤ 100) — the number of vertexes in a graph. The next n lines define the graph by an adjacency matrix: the j-th character in the i-st line is equal to 1 if there is an arc from vertex i to the vertex j else it is equal to 0. It is guaranteed that the graph doesn't contain loops. The next line contains a single integer m (2 ≤ m ≤ 10^6) — the number of vertexes in the path. The next line contains m integers p_1, p_2, …, p_m (1 ≤ p_i ≤ n) — the sequence of vertexes in the path. It is guaranteed that for any 1 ≤ i < m there is an arc from p_i to p_{i+1}. Output In the first line output a single integer k (2 ≤ k ≤ m) — the length of the shortest good subsequence. In the second line output k integers v_1, …, v_k (1 ≤ v_i ≤ n) — the vertexes in the subsequence. If there are multiple shortest subsequences, print any. Any two consecutive numbers should be distinct. Examples Input 4 0110 0010 0001 1000 4 1 2 3 4 Output 3 1 2 4 Input 4 0110 0010 1001 1000 20 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 Output 11 1 2 4 2 4 2 4 2 4 2 4 Input 3 011 101 110 7 1 2 3 1 3 2 1 Output 7 1 2 3 1 3 2 1 Input 4 0110 0001 0001 1000 3 1 2 4 Output 2 1 4 Note Below you can see the graph from the first example: <image> The given path is passing through vertexes 1, 2, 3, 4. The sequence 1-2-4 is good because it is the subsequence of the given path, its first and the last elements are equal to the first and the last elements of the given path respectively, and the shortest path passing through vertexes 1, 2 and 4 in that order is 1-2-3-4. Note that subsequences 1-4 and 1-3-4 aren't good because in both cases the shortest path passing through the vertexes of these sequences is 1-3-4. In the third example, the graph is full so any sequence of vertexes in which any two consecutive elements are distinct defines a path consisting of the same number of vertexes. In the fourth example, the paths 1-2-4 and 1-3-4 are the shortest paths passing through the vertexes 1 and 4.
instruction
0
53,139
13
106,278
Tags: dp, graphs, greedy, shortest paths Correct Solution: ``` # TAIWAN NUMBER ONE!!!!!!!!!!!!!!!!!!! # TAIWAN NUMBER ONE!!!!!!!!!!!!!!!!!!! # TAIWAN NUMBER ONE!!!!!!!!!!!!!!!!!!! from sys import stdin, stdout from collections import defaultdict import math import copy #T = int(input()) N = int(input()) #s = input() #print(N) #N,L,R = [int(x) for x in stdin.readline().split()] #arr = [int(x) for x in stdin.readline().split()] data = [] diff_paths = {} for s in range(N): for d in range(N): if s==d: diff_paths[(s+1,d+1)] = 0 else: diff_paths[(s+1,d+1)] = 9999 for i in range(N): s = input() data.append(s) for j in range(N): if s[j]=='1': diff_paths[(i+1,j+1)] = 1 V = int(input()) arr = [int(x) for x in stdin.readline().split()] for k in range(1, N+1): for i in range(1, N+1): for j in range(1, N+1): if diff_paths[(i,j)]>diff_paths[(i,k)]+diff_paths[(k,j)]: diff_paths[(i,j)] = diff_paths[(i,k)] + diff_paths[(k,j)] #print(diff_paths) ans = [arr[0]] start = arr[0] L = 0 for i in range(1,V): end = arr[i] if diff_paths[(start,end)]==L+1: L += 1 else: ans.append(arr[i-1]) start = arr[i-1] L = 1 ans.append(arr[-1]) print(len(ans)) print(*ans) ```
output
1
53,139
13
106,279
Provide tags and a correct Python 3 solution for this coding contest problem. The main characters have been omitted to be short. You are given a directed unweighted graph without loops with n vertexes and a path in it (that path is not necessary simple) given by a sequence p_1, p_2, …, p_m of m vertexes; for each 1 ≤ i < m there is an arc from p_i to p_{i+1}. Define the sequence v_1, v_2, …, v_k of k vertexes as good, if v is a subsequence of p, v_1 = p_1, v_k = p_m, and p is one of the shortest paths passing through the vertexes v_1, …, v_k in that order. A sequence a is a subsequence of a sequence b if a can be obtained from b by deletion of several (possibly, zero or all) elements. It is obvious that the sequence p is good but your task is to find the shortest good subsequence. If there are multiple shortest good subsequences, output any of them. Input The first line contains a single integer n (2 ≤ n ≤ 100) — the number of vertexes in a graph. The next n lines define the graph by an adjacency matrix: the j-th character in the i-st line is equal to 1 if there is an arc from vertex i to the vertex j else it is equal to 0. It is guaranteed that the graph doesn't contain loops. The next line contains a single integer m (2 ≤ m ≤ 10^6) — the number of vertexes in the path. The next line contains m integers p_1, p_2, …, p_m (1 ≤ p_i ≤ n) — the sequence of vertexes in the path. It is guaranteed that for any 1 ≤ i < m there is an arc from p_i to p_{i+1}. Output In the first line output a single integer k (2 ≤ k ≤ m) — the length of the shortest good subsequence. In the second line output k integers v_1, …, v_k (1 ≤ v_i ≤ n) — the vertexes in the subsequence. If there are multiple shortest subsequences, print any. Any two consecutive numbers should be distinct. Examples Input 4 0110 0010 0001 1000 4 1 2 3 4 Output 3 1 2 4 Input 4 0110 0010 1001 1000 20 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 Output 11 1 2 4 2 4 2 4 2 4 2 4 Input 3 011 101 110 7 1 2 3 1 3 2 1 Output 7 1 2 3 1 3 2 1 Input 4 0110 0001 0001 1000 3 1 2 4 Output 2 1 4 Note Below you can see the graph from the first example: <image> The given path is passing through vertexes 1, 2, 3, 4. The sequence 1-2-4 is good because it is the subsequence of the given path, its first and the last elements are equal to the first and the last elements of the given path respectively, and the shortest path passing through vertexes 1, 2 and 4 in that order is 1-2-3-4. Note that subsequences 1-4 and 1-3-4 aren't good because in both cases the shortest path passing through the vertexes of these sequences is 1-3-4. In the third example, the graph is full so any sequence of vertexes in which any two consecutive elements are distinct defines a path consisting of the same number of vertexes. In the fourth example, the paths 1-2-4 and 1-3-4 are the shortest paths passing through the vertexes 1 and 4.
instruction
0
53,140
13
106,280
Tags: dp, graphs, greedy, shortest paths Correct Solution: ``` import sys input = sys.stdin.readline from collections import deque class Graph(object): """docstring for Graph""" def __init__(self, n): self.n = n self.graph = [[] for i in range(n)] def bfs(self, root): queue = [root,-1] queue = deque(queue) vis = [0]*n d = [0]*n t = 1 while len(queue)!=1: element = queue.popleft() if element==-1: queue.append(-1) t+=1 continue vis[element] = 1 for i in self.graph[element]: if vis[i]==0: queue.append(i) d[i] = t vis[i] = 1 # print (d, root) return d n = int(input()) g = Graph(n) for i in range(n): s=input() for j in range(n): if s[j]=="1": g.graph[i].append(j) k = int(input()) a = list(map(int,input().split())) dist=[] for i in range(n): dist.append(g.bfs(i)) # print (g.graph) # for i in dist: # print (*i) i = 1 root = a[0]-1 d = 1 count = 1 ans = [a[0]] while i<k: # print (root,i,d) if dist[root][a[i]-1]!=d: count += 1 root = a[i-1]-1 ans.append(a[i-1]) d = 1 else: i += 1 d += 1 ans.append(a[-1]) count += 1 print (count) print (*ans) ```
output
1
53,140
13
106,281
Provide tags and a correct Python 3 solution for this coding contest problem. The main characters have been omitted to be short. You are given a directed unweighted graph without loops with n vertexes and a path in it (that path is not necessary simple) given by a sequence p_1, p_2, …, p_m of m vertexes; for each 1 ≤ i < m there is an arc from p_i to p_{i+1}. Define the sequence v_1, v_2, …, v_k of k vertexes as good, if v is a subsequence of p, v_1 = p_1, v_k = p_m, and p is one of the shortest paths passing through the vertexes v_1, …, v_k in that order. A sequence a is a subsequence of a sequence b if a can be obtained from b by deletion of several (possibly, zero or all) elements. It is obvious that the sequence p is good but your task is to find the shortest good subsequence. If there are multiple shortest good subsequences, output any of them. Input The first line contains a single integer n (2 ≤ n ≤ 100) — the number of vertexes in a graph. The next n lines define the graph by an adjacency matrix: the j-th character in the i-st line is equal to 1 if there is an arc from vertex i to the vertex j else it is equal to 0. It is guaranteed that the graph doesn't contain loops. The next line contains a single integer m (2 ≤ m ≤ 10^6) — the number of vertexes in the path. The next line contains m integers p_1, p_2, …, p_m (1 ≤ p_i ≤ n) — the sequence of vertexes in the path. It is guaranteed that for any 1 ≤ i < m there is an arc from p_i to p_{i+1}. Output In the first line output a single integer k (2 ≤ k ≤ m) — the length of the shortest good subsequence. In the second line output k integers v_1, …, v_k (1 ≤ v_i ≤ n) — the vertexes in the subsequence. If there are multiple shortest subsequences, print any. Any two consecutive numbers should be distinct. Examples Input 4 0110 0010 0001 1000 4 1 2 3 4 Output 3 1 2 4 Input 4 0110 0010 1001 1000 20 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 Output 11 1 2 4 2 4 2 4 2 4 2 4 Input 3 011 101 110 7 1 2 3 1 3 2 1 Output 7 1 2 3 1 3 2 1 Input 4 0110 0001 0001 1000 3 1 2 4 Output 2 1 4 Note Below you can see the graph from the first example: <image> The given path is passing through vertexes 1, 2, 3, 4. The sequence 1-2-4 is good because it is the subsequence of the given path, its first and the last elements are equal to the first and the last elements of the given path respectively, and the shortest path passing through vertexes 1, 2 and 4 in that order is 1-2-3-4. Note that subsequences 1-4 and 1-3-4 aren't good because in both cases the shortest path passing through the vertexes of these sequences is 1-3-4. In the third example, the graph is full so any sequence of vertexes in which any two consecutive elements are distinct defines a path consisting of the same number of vertexes. In the fourth example, the paths 1-2-4 and 1-3-4 are the shortest paths passing through the vertexes 1 and 4.
instruction
0
53,141
13
106,282
Tags: dp, graphs, greedy, shortest paths Correct Solution: ``` from sys import stdin,stdout input=stdin.readline print=stdout.write n=int(input()) inf=200 g=[] g=[[0]*n for i in range(n)] for i in range(n): s=input() for j in range(n): g[i][j]=1 if int(s[j]) else inf if i==j: g[i][j]=0 for k in range(n): for i in range(n): for j in range(n): g[i][j]=min(g[i][j],g[k][j]+g[i][k]) m=int(input()) p=list(map(int,input().split())) ans=[p[0]] for i in range(1,m-1): if g[ans[-1]-1][p[i+1]-1]-g[ans[-1]-1][p[i]-1]!=1: ans.append(p[i]) ans.append(p[-1]) print(str(len(ans))) print('\n') print(' '.join(str(i) for i in ans)) #print('\n') ```
output
1
53,141
13
106,283
Provide tags and a correct Python 3 solution for this coding contest problem. The main characters have been omitted to be short. You are given a directed unweighted graph without loops with n vertexes and a path in it (that path is not necessary simple) given by a sequence p_1, p_2, …, p_m of m vertexes; for each 1 ≤ i < m there is an arc from p_i to p_{i+1}. Define the sequence v_1, v_2, …, v_k of k vertexes as good, if v is a subsequence of p, v_1 = p_1, v_k = p_m, and p is one of the shortest paths passing through the vertexes v_1, …, v_k in that order. A sequence a is a subsequence of a sequence b if a can be obtained from b by deletion of several (possibly, zero or all) elements. It is obvious that the sequence p is good but your task is to find the shortest good subsequence. If there are multiple shortest good subsequences, output any of them. Input The first line contains a single integer n (2 ≤ n ≤ 100) — the number of vertexes in a graph. The next n lines define the graph by an adjacency matrix: the j-th character in the i-st line is equal to 1 if there is an arc from vertex i to the vertex j else it is equal to 0. It is guaranteed that the graph doesn't contain loops. The next line contains a single integer m (2 ≤ m ≤ 10^6) — the number of vertexes in the path. The next line contains m integers p_1, p_2, …, p_m (1 ≤ p_i ≤ n) — the sequence of vertexes in the path. It is guaranteed that for any 1 ≤ i < m there is an arc from p_i to p_{i+1}. Output In the first line output a single integer k (2 ≤ k ≤ m) — the length of the shortest good subsequence. In the second line output k integers v_1, …, v_k (1 ≤ v_i ≤ n) — the vertexes in the subsequence. If there are multiple shortest subsequences, print any. Any two consecutive numbers should be distinct. Examples Input 4 0110 0010 0001 1000 4 1 2 3 4 Output 3 1 2 4 Input 4 0110 0010 1001 1000 20 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 Output 11 1 2 4 2 4 2 4 2 4 2 4 Input 3 011 101 110 7 1 2 3 1 3 2 1 Output 7 1 2 3 1 3 2 1 Input 4 0110 0001 0001 1000 3 1 2 4 Output 2 1 4 Note Below you can see the graph from the first example: <image> The given path is passing through vertexes 1, 2, 3, 4. The sequence 1-2-4 is good because it is the subsequence of the given path, its first and the last elements are equal to the first and the last elements of the given path respectively, and the shortest path passing through vertexes 1, 2 and 4 in that order is 1-2-3-4. Note that subsequences 1-4 and 1-3-4 aren't good because in both cases the shortest path passing through the vertexes of these sequences is 1-3-4. In the third example, the graph is full so any sequence of vertexes in which any two consecutive elements are distinct defines a path consisting of the same number of vertexes. In the fourth example, the paths 1-2-4 and 1-3-4 are the shortest paths passing through the vertexes 1 and 4.
instruction
0
53,142
13
106,284
Tags: dp, graphs, greedy, shortest paths Correct Solution: ``` n=int(input()) l=[] p=[] ans=[] for i in range(n): l.append(list(map(int,input()))) for i in range(n): for j in range(n): if i!=j and l[i][j]==0: l[i][j]=9999999 for k in range(n): for i in range(n): for j in range(n): if l[i][j]>l[i][k]+l[k][j]: l[i][j]=l[i][k]+l[k][j] m=int(input()) p=list(map(int,input().split(" "))) ans.append(p[0]) dis=0 for i in range(1,m): dis=dis+l[p[i-1]-1][p[i]-1] if(dis>l[ans[len(ans)-1]-1][p[i]-1]): ans.append(p[i-1]) dis=l[ans[len(ans)-1]-1][p[i]-1] ans.append(p[m-1]) print(len(ans)) for i in ans: print(i,end=" ") ```
output
1
53,142
13
106,285
Provide tags and a correct Python 3 solution for this coding contest problem. The main characters have been omitted to be short. You are given a directed unweighted graph without loops with n vertexes and a path in it (that path is not necessary simple) given by a sequence p_1, p_2, …, p_m of m vertexes; for each 1 ≤ i < m there is an arc from p_i to p_{i+1}. Define the sequence v_1, v_2, …, v_k of k vertexes as good, if v is a subsequence of p, v_1 = p_1, v_k = p_m, and p is one of the shortest paths passing through the vertexes v_1, …, v_k in that order. A sequence a is a subsequence of a sequence b if a can be obtained from b by deletion of several (possibly, zero or all) elements. It is obvious that the sequence p is good but your task is to find the shortest good subsequence. If there are multiple shortest good subsequences, output any of them. Input The first line contains a single integer n (2 ≤ n ≤ 100) — the number of vertexes in a graph. The next n lines define the graph by an adjacency matrix: the j-th character in the i-st line is equal to 1 if there is an arc from vertex i to the vertex j else it is equal to 0. It is guaranteed that the graph doesn't contain loops. The next line contains a single integer m (2 ≤ m ≤ 10^6) — the number of vertexes in the path. The next line contains m integers p_1, p_2, …, p_m (1 ≤ p_i ≤ n) — the sequence of vertexes in the path. It is guaranteed that for any 1 ≤ i < m there is an arc from p_i to p_{i+1}. Output In the first line output a single integer k (2 ≤ k ≤ m) — the length of the shortest good subsequence. In the second line output k integers v_1, …, v_k (1 ≤ v_i ≤ n) — the vertexes in the subsequence. If there are multiple shortest subsequences, print any. Any two consecutive numbers should be distinct. Examples Input 4 0110 0010 0001 1000 4 1 2 3 4 Output 3 1 2 4 Input 4 0110 0010 1001 1000 20 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 Output 11 1 2 4 2 4 2 4 2 4 2 4 Input 3 011 101 110 7 1 2 3 1 3 2 1 Output 7 1 2 3 1 3 2 1 Input 4 0110 0001 0001 1000 3 1 2 4 Output 2 1 4 Note Below you can see the graph from the first example: <image> The given path is passing through vertexes 1, 2, 3, 4. The sequence 1-2-4 is good because it is the subsequence of the given path, its first and the last elements are equal to the first and the last elements of the given path respectively, and the shortest path passing through vertexes 1, 2 and 4 in that order is 1-2-3-4. Note that subsequences 1-4 and 1-3-4 aren't good because in both cases the shortest path passing through the vertexes of these sequences is 1-3-4. In the third example, the graph is full so any sequence of vertexes in which any two consecutive elements are distinct defines a path consisting of the same number of vertexes. In the fourth example, the paths 1-2-4 and 1-3-4 are the shortest paths passing through the vertexes 1 and 4.
instruction
0
53,143
13
106,286
Tags: dp, graphs, greedy, shortest paths Correct Solution: ``` from heapq import heapify, heappush as hpush, heappop as hpop N = int(input()) X = [[] for _ in range(N)] for i in range(N): s = input() for j in range(N): if s[j] == "1": X[i].append((j, 1)) def dijkstra(n, E, i0=0): h = [[0, i0]] D = [-1] * n done = [0] * n D[i0] = 0 while h: d, i = hpop(h) done[i] = 1 for j, w in E[i]: nd = d + w if D[j] < 0 or D[j] >= nd: if done[j] == 0: hpush(h, [nd, j]) D[j] = nd return [d if d >= 0 else 1<<50 for d in D] Y = [] for i in range(N): Y.append(dijkstra(N, X, i)) # print("Y =", Y) M = int(input()) V = [int(a)-1 for a in input().split()] a = 0 b = 1 t = Y[V[a]][V[b]] ANS = [V[a]+1] while b < M: if Y[V[a]][V[b]] < t: a = b-1 ANS.append(V[a]+1) t = Y[V[a]][V[b]] elif b == M-1: break else: t += Y[V[b]][V[b+1]] b += 1 ANS.append(V[M-1]+1) print(len(ANS)) print(*ANS) ```
output
1
53,143
13
106,287
Provide tags and a correct Python 3 solution for this coding contest problem. The main characters have been omitted to be short. You are given a directed unweighted graph without loops with n vertexes and a path in it (that path is not necessary simple) given by a sequence p_1, p_2, …, p_m of m vertexes; for each 1 ≤ i < m there is an arc from p_i to p_{i+1}. Define the sequence v_1, v_2, …, v_k of k vertexes as good, if v is a subsequence of p, v_1 = p_1, v_k = p_m, and p is one of the shortest paths passing through the vertexes v_1, …, v_k in that order. A sequence a is a subsequence of a sequence b if a can be obtained from b by deletion of several (possibly, zero or all) elements. It is obvious that the sequence p is good but your task is to find the shortest good subsequence. If there are multiple shortest good subsequences, output any of them. Input The first line contains a single integer n (2 ≤ n ≤ 100) — the number of vertexes in a graph. The next n lines define the graph by an adjacency matrix: the j-th character in the i-st line is equal to 1 if there is an arc from vertex i to the vertex j else it is equal to 0. It is guaranteed that the graph doesn't contain loops. The next line contains a single integer m (2 ≤ m ≤ 10^6) — the number of vertexes in the path. The next line contains m integers p_1, p_2, …, p_m (1 ≤ p_i ≤ n) — the sequence of vertexes in the path. It is guaranteed that for any 1 ≤ i < m there is an arc from p_i to p_{i+1}. Output In the first line output a single integer k (2 ≤ k ≤ m) — the length of the shortest good subsequence. In the second line output k integers v_1, …, v_k (1 ≤ v_i ≤ n) — the vertexes in the subsequence. If there are multiple shortest subsequences, print any. Any two consecutive numbers should be distinct. Examples Input 4 0110 0010 0001 1000 4 1 2 3 4 Output 3 1 2 4 Input 4 0110 0010 1001 1000 20 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 Output 11 1 2 4 2 4 2 4 2 4 2 4 Input 3 011 101 110 7 1 2 3 1 3 2 1 Output 7 1 2 3 1 3 2 1 Input 4 0110 0001 0001 1000 3 1 2 4 Output 2 1 4 Note Below you can see the graph from the first example: <image> The given path is passing through vertexes 1, 2, 3, 4. The sequence 1-2-4 is good because it is the subsequence of the given path, its first and the last elements are equal to the first and the last elements of the given path respectively, and the shortest path passing through vertexes 1, 2 and 4 in that order is 1-2-3-4. Note that subsequences 1-4 and 1-3-4 aren't good because in both cases the shortest path passing through the vertexes of these sequences is 1-3-4. In the third example, the graph is full so any sequence of vertexes in which any two consecutive elements are distinct defines a path consisting of the same number of vertexes. In the fourth example, the paths 1-2-4 and 1-3-4 are the shortest paths passing through the vertexes 1 and 4.
instruction
0
53,144
13
106,288
Tags: dp, graphs, greedy, shortest paths Correct Solution: ``` import sys from collections import defaultdict graph=defaultdict(list) n=int(sys.stdin.readline()) dp=[[0 for _ in range(n)] for x in range(n)] for i in range(n): s=sys.stdin.readline()[:-1] #print(s,'s') for j in range(n): if s[j]=='1': dp[i][j]=1 else: dp[i][j]=float('inf') #print(dp,'dp') for i in range(n): dp[i][i]=0 for k in range(n): for i in range(n): for j in range(n): if dp[i][k]+dp[k][j]<dp[i][j]: dp[i][j]=dp[i][k]+dp[k][j] nex=[[i for i in dp[j]] for j in range(n)] #print(dp,'final pairs') m=int(sys.stdin.readline()) p=list(map(int,sys.stdin.readline().split())) ans=[p[0]] last=0 for i in range(1,m): if dp[ans[-1]-1][p[i]-1]==(i-last): #print(p[i],'p[i]') pass else: last=i-1 ans.append(p[i-1]) i,last=1,0 '''while i<m: if dp[ans[-1]-1][p[i]-1]==i-last: i+=1 else: print(last,'last',i,'i') ans.append(p[last]) last+=1''' ans.append(p[-1]) print(len(ans)) print(*ans) ```
output
1
53,144
13
106,289
Provide tags and a correct Python 3 solution for this coding contest problem. The main characters have been omitted to be short. You are given a directed unweighted graph without loops with n vertexes and a path in it (that path is not necessary simple) given by a sequence p_1, p_2, …, p_m of m vertexes; for each 1 ≤ i < m there is an arc from p_i to p_{i+1}. Define the sequence v_1, v_2, …, v_k of k vertexes as good, if v is a subsequence of p, v_1 = p_1, v_k = p_m, and p is one of the shortest paths passing through the vertexes v_1, …, v_k in that order. A sequence a is a subsequence of a sequence b if a can be obtained from b by deletion of several (possibly, zero or all) elements. It is obvious that the sequence p is good but your task is to find the shortest good subsequence. If there are multiple shortest good subsequences, output any of them. Input The first line contains a single integer n (2 ≤ n ≤ 100) — the number of vertexes in a graph. The next n lines define the graph by an adjacency matrix: the j-th character in the i-st line is equal to 1 if there is an arc from vertex i to the vertex j else it is equal to 0. It is guaranteed that the graph doesn't contain loops. The next line contains a single integer m (2 ≤ m ≤ 10^6) — the number of vertexes in the path. The next line contains m integers p_1, p_2, …, p_m (1 ≤ p_i ≤ n) — the sequence of vertexes in the path. It is guaranteed that for any 1 ≤ i < m there is an arc from p_i to p_{i+1}. Output In the first line output a single integer k (2 ≤ k ≤ m) — the length of the shortest good subsequence. In the second line output k integers v_1, …, v_k (1 ≤ v_i ≤ n) — the vertexes in the subsequence. If there are multiple shortest subsequences, print any. Any two consecutive numbers should be distinct. Examples Input 4 0110 0010 0001 1000 4 1 2 3 4 Output 3 1 2 4 Input 4 0110 0010 1001 1000 20 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 Output 11 1 2 4 2 4 2 4 2 4 2 4 Input 3 011 101 110 7 1 2 3 1 3 2 1 Output 7 1 2 3 1 3 2 1 Input 4 0110 0001 0001 1000 3 1 2 4 Output 2 1 4 Note Below you can see the graph from the first example: <image> The given path is passing through vertexes 1, 2, 3, 4. The sequence 1-2-4 is good because it is the subsequence of the given path, its first and the last elements are equal to the first and the last elements of the given path respectively, and the shortest path passing through vertexes 1, 2 and 4 in that order is 1-2-3-4. Note that subsequences 1-4 and 1-3-4 aren't good because in both cases the shortest path passing through the vertexes of these sequences is 1-3-4. In the third example, the graph is full so any sequence of vertexes in which any two consecutive elements are distinct defines a path consisting of the same number of vertexes. In the fourth example, the paths 1-2-4 and 1-3-4 are the shortest paths passing through the vertexes 1 and 4.
instruction
0
53,145
13
106,290
Tags: dp, graphs, greedy, shortest paths Correct Solution: ``` import sys def main(): INF = int(1e9) n = int(sys.stdin.readline()) g = [[]] * n for i in range(n): s = sys.stdin.readline().strip() sg = list(map(int, list(s))) g[i] = sg m = int(sys.stdin.readline()) p = list(map(lambda x: int(x) - 1, sys.stdin.readline().split())) for i in range(n): for j in range(n): if i != j and g[i][j] == 0: g[i][j] = INF for k in range(n): for i in range(n): for j in range(n): g[i][j] = min(g[i][j], g[i][k] + g[k][j]) MAXM = int(1e6) p_len = len(p) ans = [0] * p_len ans_ind = 0 ind = 0 while ind < p_len: #~ print(ind) cur = p[ind] ans[ans_ind] = cur ans_ind += 1 new = ind + 1 while new < p_len and g[cur][p[new]] == new - ind: new += 1 if new == p_len: ans[ans_ind] = p[-1] ans_ind += 1 break if g[cur][p[new]] != new - ind: new -= 1 ind = new ans = [x + 1 for x in ans[:ans_ind]] print(len(ans)) print(' '.join(map(str, ans[:ans_ind]))) if __name__ == '__main__': main() ```
output
1
53,145
13
106,291
Provide tags and a correct Python 3 solution for this coding contest problem. The main characters have been omitted to be short. You are given a directed unweighted graph without loops with n vertexes and a path in it (that path is not necessary simple) given by a sequence p_1, p_2, …, p_m of m vertexes; for each 1 ≤ i < m there is an arc from p_i to p_{i+1}. Define the sequence v_1, v_2, …, v_k of k vertexes as good, if v is a subsequence of p, v_1 = p_1, v_k = p_m, and p is one of the shortest paths passing through the vertexes v_1, …, v_k in that order. A sequence a is a subsequence of a sequence b if a can be obtained from b by deletion of several (possibly, zero or all) elements. It is obvious that the sequence p is good but your task is to find the shortest good subsequence. If there are multiple shortest good subsequences, output any of them. Input The first line contains a single integer n (2 ≤ n ≤ 100) — the number of vertexes in a graph. The next n lines define the graph by an adjacency matrix: the j-th character in the i-st line is equal to 1 if there is an arc from vertex i to the vertex j else it is equal to 0. It is guaranteed that the graph doesn't contain loops. The next line contains a single integer m (2 ≤ m ≤ 10^6) — the number of vertexes in the path. The next line contains m integers p_1, p_2, …, p_m (1 ≤ p_i ≤ n) — the sequence of vertexes in the path. It is guaranteed that for any 1 ≤ i < m there is an arc from p_i to p_{i+1}. Output In the first line output a single integer k (2 ≤ k ≤ m) — the length of the shortest good subsequence. In the second line output k integers v_1, …, v_k (1 ≤ v_i ≤ n) — the vertexes in the subsequence. If there are multiple shortest subsequences, print any. Any two consecutive numbers should be distinct. Examples Input 4 0110 0010 0001 1000 4 1 2 3 4 Output 3 1 2 4 Input 4 0110 0010 1001 1000 20 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 Output 11 1 2 4 2 4 2 4 2 4 2 4 Input 3 011 101 110 7 1 2 3 1 3 2 1 Output 7 1 2 3 1 3 2 1 Input 4 0110 0001 0001 1000 3 1 2 4 Output 2 1 4 Note Below you can see the graph from the first example: <image> The given path is passing through vertexes 1, 2, 3, 4. The sequence 1-2-4 is good because it is the subsequence of the given path, its first and the last elements are equal to the first and the last elements of the given path respectively, and the shortest path passing through vertexes 1, 2 and 4 in that order is 1-2-3-4. Note that subsequences 1-4 and 1-3-4 aren't good because in both cases the shortest path passing through the vertexes of these sequences is 1-3-4. In the third example, the graph is full so any sequence of vertexes in which any two consecutive elements are distinct defines a path consisting of the same number of vertexes. In the fourth example, the paths 1-2-4 and 1-3-4 are the shortest paths passing through the vertexes 1 and 4.
instruction
0
53,146
13
106,292
Tags: dp, graphs, greedy, shortest paths Correct Solution: ``` n = int(input()) g = [] def bfs(src): q = [] dist = [] visited = [] for i in range(n): visited.append(False) dist.append(1e18) dist[src] = 0 visited[src] = True q.append(src) done = True while q: src = q.pop(0) for i in g[src]: if visited[i] == False: visited[i] = True dist[i] = dist[src] + 1 q.append(i) return dist for i in range(n): #adjacency matrix input t = input() g.append([]) for j in range(len(t)): if t[j] == '1': g[i].append(j) m = int(input()) p = list(map(int, input().split())) for i in range(m): p[i] -= 1 dist = [] for i in range(n): dist.append(bfs(i)) ans = [p[0]] k = 0 for i in range(1, m): if (dist[ans[-1]][p[i]] == 1e18 or dist[ans[-1]][p[i]] < (i-k)): ans.append(p[i-1]) k = i - 1 ans.append(p[-1]) l = len(ans) for i in range(l): ans[i] += 1 ans[i] = str(ans[i]) print(len(ans)) print(' '.join(ans)) ```
output
1
53,146
13
106,293
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The main characters have been omitted to be short. You are given a directed unweighted graph without loops with n vertexes and a path in it (that path is not necessary simple) given by a sequence p_1, p_2, …, p_m of m vertexes; for each 1 ≤ i < m there is an arc from p_i to p_{i+1}. Define the sequence v_1, v_2, …, v_k of k vertexes as good, if v is a subsequence of p, v_1 = p_1, v_k = p_m, and p is one of the shortest paths passing through the vertexes v_1, …, v_k in that order. A sequence a is a subsequence of a sequence b if a can be obtained from b by deletion of several (possibly, zero or all) elements. It is obvious that the sequence p is good but your task is to find the shortest good subsequence. If there are multiple shortest good subsequences, output any of them. Input The first line contains a single integer n (2 ≤ n ≤ 100) — the number of vertexes in a graph. The next n lines define the graph by an adjacency matrix: the j-th character in the i-st line is equal to 1 if there is an arc from vertex i to the vertex j else it is equal to 0. It is guaranteed that the graph doesn't contain loops. The next line contains a single integer m (2 ≤ m ≤ 10^6) — the number of vertexes in the path. The next line contains m integers p_1, p_2, …, p_m (1 ≤ p_i ≤ n) — the sequence of vertexes in the path. It is guaranteed that for any 1 ≤ i < m there is an arc from p_i to p_{i+1}. Output In the first line output a single integer k (2 ≤ k ≤ m) — the length of the shortest good subsequence. In the second line output k integers v_1, …, v_k (1 ≤ v_i ≤ n) — the vertexes in the subsequence. If there are multiple shortest subsequences, print any. Any two consecutive numbers should be distinct. Examples Input 4 0110 0010 0001 1000 4 1 2 3 4 Output 3 1 2 4 Input 4 0110 0010 1001 1000 20 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 Output 11 1 2 4 2 4 2 4 2 4 2 4 Input 3 011 101 110 7 1 2 3 1 3 2 1 Output 7 1 2 3 1 3 2 1 Input 4 0110 0001 0001 1000 3 1 2 4 Output 2 1 4 Note Below you can see the graph from the first example: <image> The given path is passing through vertexes 1, 2, 3, 4. The sequence 1-2-4 is good because it is the subsequence of the given path, its first and the last elements are equal to the first and the last elements of the given path respectively, and the shortest path passing through vertexes 1, 2 and 4 in that order is 1-2-3-4. Note that subsequences 1-4 and 1-3-4 aren't good because in both cases the shortest path passing through the vertexes of these sequences is 1-3-4. In the third example, the graph is full so any sequence of vertexes in which any two consecutive elements are distinct defines a path consisting of the same number of vertexes. In the fourth example, the paths 1-2-4 and 1-3-4 are the shortest paths passing through the vertexes 1 and 4. Submitted Solution: ``` from sys import stdin input=stdin.readline #import bisect #i = bisect.bisect_left(a, k) a=[] #ans=0 n=int(input()) for _ in range (n): s=input() a.append(s) m=int(input()) #n,k=map(int, input().split()) b=list(map(int, input().split())) c=[0]*m k=0 for i in range(1,m-1): if k==1: k=0 continue if a[b[i-1]-1][b[i+1]-1]=='0' and b[i-1]!=b[i+1]: k=1 c[i]=1 print(c.count(0)) for i in range(m): if c[i]==0: print(b[i],end=" ") #YOUR CODE HERE ```
instruction
0
53,147
13
106,294
Yes
output
1
53,147
13
106,295
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The main characters have been omitted to be short. You are given a directed unweighted graph without loops with n vertexes and a path in it (that path is not necessary simple) given by a sequence p_1, p_2, …, p_m of m vertexes; for each 1 ≤ i < m there is an arc from p_i to p_{i+1}. Define the sequence v_1, v_2, …, v_k of k vertexes as good, if v is a subsequence of p, v_1 = p_1, v_k = p_m, and p is one of the shortest paths passing through the vertexes v_1, …, v_k in that order. A sequence a is a subsequence of a sequence b if a can be obtained from b by deletion of several (possibly, zero or all) elements. It is obvious that the sequence p is good but your task is to find the shortest good subsequence. If there are multiple shortest good subsequences, output any of them. Input The first line contains a single integer n (2 ≤ n ≤ 100) — the number of vertexes in a graph. The next n lines define the graph by an adjacency matrix: the j-th character in the i-st line is equal to 1 if there is an arc from vertex i to the vertex j else it is equal to 0. It is guaranteed that the graph doesn't contain loops. The next line contains a single integer m (2 ≤ m ≤ 10^6) — the number of vertexes in the path. The next line contains m integers p_1, p_2, …, p_m (1 ≤ p_i ≤ n) — the sequence of vertexes in the path. It is guaranteed that for any 1 ≤ i < m there is an arc from p_i to p_{i+1}. Output In the first line output a single integer k (2 ≤ k ≤ m) — the length of the shortest good subsequence. In the second line output k integers v_1, …, v_k (1 ≤ v_i ≤ n) — the vertexes in the subsequence. If there are multiple shortest subsequences, print any. Any two consecutive numbers should be distinct. Examples Input 4 0110 0010 0001 1000 4 1 2 3 4 Output 3 1 2 4 Input 4 0110 0010 1001 1000 20 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 Output 11 1 2 4 2 4 2 4 2 4 2 4 Input 3 011 101 110 7 1 2 3 1 3 2 1 Output 7 1 2 3 1 3 2 1 Input 4 0110 0001 0001 1000 3 1 2 4 Output 2 1 4 Note Below you can see the graph from the first example: <image> The given path is passing through vertexes 1, 2, 3, 4. The sequence 1-2-4 is good because it is the subsequence of the given path, its first and the last elements are equal to the first and the last elements of the given path respectively, and the shortest path passing through vertexes 1, 2 and 4 in that order is 1-2-3-4. Note that subsequences 1-4 and 1-3-4 aren't good because in both cases the shortest path passing through the vertexes of these sequences is 1-3-4. In the third example, the graph is full so any sequence of vertexes in which any two consecutive elements are distinct defines a path consisting of the same number of vertexes. In the fourth example, the paths 1-2-4 and 1-3-4 are the shortest paths passing through the vertexes 1 and 4. Submitted Solution: ``` N = int(1e6+3) n = int(input()) dis = list([N] * n for _ in range(n)) for i in range(n): for j in range(n): if i == j: dis[i][j] = 0 for i in range(n): s = input() for j in range(n): if s[j] == '1': dis[i][j] = 1 for k in range(n): for i in range(n): for j in range(n): dis[i][j] = min(dis[i][j], dis[i][k] + dis[k][j]) m = int(input()) arr = list(map(int, input().split())) for i in range(m): arr[i] -= 1 e, cnt = m-1, 0 for i in range(m-3, -1, -1): x, y, z = arr[i], arr[i+1], arr[e] if dis[x][z] < dis[x][y] + dis[y][z]: e = i + 1 else: arr[i+1] = -1 cnt += 1 print(m - cnt) print(*[i+1 for i in arr if i != -1]) ```
instruction
0
53,148
13
106,296
Yes
output
1
53,148
13
106,297
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The main characters have been omitted to be short. You are given a directed unweighted graph without loops with n vertexes and a path in it (that path is not necessary simple) given by a sequence p_1, p_2, …, p_m of m vertexes; for each 1 ≤ i < m there is an arc from p_i to p_{i+1}. Define the sequence v_1, v_2, …, v_k of k vertexes as good, if v is a subsequence of p, v_1 = p_1, v_k = p_m, and p is one of the shortest paths passing through the vertexes v_1, …, v_k in that order. A sequence a is a subsequence of a sequence b if a can be obtained from b by deletion of several (possibly, zero or all) elements. It is obvious that the sequence p is good but your task is to find the shortest good subsequence. If there are multiple shortest good subsequences, output any of them. Input The first line contains a single integer n (2 ≤ n ≤ 100) — the number of vertexes in a graph. The next n lines define the graph by an adjacency matrix: the j-th character in the i-st line is equal to 1 if there is an arc from vertex i to the vertex j else it is equal to 0. It is guaranteed that the graph doesn't contain loops. The next line contains a single integer m (2 ≤ m ≤ 10^6) — the number of vertexes in the path. The next line contains m integers p_1, p_2, …, p_m (1 ≤ p_i ≤ n) — the sequence of vertexes in the path. It is guaranteed that for any 1 ≤ i < m there is an arc from p_i to p_{i+1}. Output In the first line output a single integer k (2 ≤ k ≤ m) — the length of the shortest good subsequence. In the second line output k integers v_1, …, v_k (1 ≤ v_i ≤ n) — the vertexes in the subsequence. If there are multiple shortest subsequences, print any. Any two consecutive numbers should be distinct. Examples Input 4 0110 0010 0001 1000 4 1 2 3 4 Output 3 1 2 4 Input 4 0110 0010 1001 1000 20 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 Output 11 1 2 4 2 4 2 4 2 4 2 4 Input 3 011 101 110 7 1 2 3 1 3 2 1 Output 7 1 2 3 1 3 2 1 Input 4 0110 0001 0001 1000 3 1 2 4 Output 2 1 4 Note Below you can see the graph from the first example: <image> The given path is passing through vertexes 1, 2, 3, 4. The sequence 1-2-4 is good because it is the subsequence of the given path, its first and the last elements are equal to the first and the last elements of the given path respectively, and the shortest path passing through vertexes 1, 2 and 4 in that order is 1-2-3-4. Note that subsequences 1-4 and 1-3-4 aren't good because in both cases the shortest path passing through the vertexes of these sequences is 1-3-4. In the third example, the graph is full so any sequence of vertexes in which any two consecutive elements are distinct defines a path consisting of the same number of vertexes. In the fourth example, the paths 1-2-4 and 1-3-4 are the shortest paths passing through the vertexes 1 and 4. Submitted Solution: ``` def warshall_floyd(d): #d[i][j]: iからjへの最短距離 for k in range(n): for i in range(n): for j in range(n): d[i][j] = min(d[i][j],d[i][k] + d[k][j]) return d n=int(input()) g=[list(input()) for _ in range(n)] d=[[float('inf')]*n for _ in range(n)] for i in range(n): for j in range(n): if g[i][j]=='1': d[i][j]=1 warshall_floyd(d) m=int(input()) arr=list(map(int,input().split())) for i in range(m): arr[i]-=1 ans=[arr[0]] pos1=0 pos2=1 pos3=2 for i in range(m-2): a,b,c=arr[pos1],arr[pos2],arr[pos3] if a!=c: if d[a][b]+d[b][c]>d[a][c]: ans.append(b) pos1=pos2 pos2=pos1+1 pos3=pos2+1 else: pos2+=1 pos3+=1 else: if d[a][b]+d[b][c]>=d[a][c]: ans.append(b) pos1=pos2 pos2=pos1+1 pos3=pos2+1 else: pos2+=1 pos3+=1 ans.append(arr[-1]) l=len(ans) for i in range(l): ans[i]+=1 print(l) print(*ans) ```
instruction
0
53,149
13
106,298
Yes
output
1
53,149
13
106,299
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The main characters have been omitted to be short. You are given a directed unweighted graph without loops with n vertexes and a path in it (that path is not necessary simple) given by a sequence p_1, p_2, …, p_m of m vertexes; for each 1 ≤ i < m there is an arc from p_i to p_{i+1}. Define the sequence v_1, v_2, …, v_k of k vertexes as good, if v is a subsequence of p, v_1 = p_1, v_k = p_m, and p is one of the shortest paths passing through the vertexes v_1, …, v_k in that order. A sequence a is a subsequence of a sequence b if a can be obtained from b by deletion of several (possibly, zero or all) elements. It is obvious that the sequence p is good but your task is to find the shortest good subsequence. If there are multiple shortest good subsequences, output any of them. Input The first line contains a single integer n (2 ≤ n ≤ 100) — the number of vertexes in a graph. The next n lines define the graph by an adjacency matrix: the j-th character in the i-st line is equal to 1 if there is an arc from vertex i to the vertex j else it is equal to 0. It is guaranteed that the graph doesn't contain loops. The next line contains a single integer m (2 ≤ m ≤ 10^6) — the number of vertexes in the path. The next line contains m integers p_1, p_2, …, p_m (1 ≤ p_i ≤ n) — the sequence of vertexes in the path. It is guaranteed that for any 1 ≤ i < m there is an arc from p_i to p_{i+1}. Output In the first line output a single integer k (2 ≤ k ≤ m) — the length of the shortest good subsequence. In the second line output k integers v_1, …, v_k (1 ≤ v_i ≤ n) — the vertexes in the subsequence. If there are multiple shortest subsequences, print any. Any two consecutive numbers should be distinct. Examples Input 4 0110 0010 0001 1000 4 1 2 3 4 Output 3 1 2 4 Input 4 0110 0010 1001 1000 20 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 Output 11 1 2 4 2 4 2 4 2 4 2 4 Input 3 011 101 110 7 1 2 3 1 3 2 1 Output 7 1 2 3 1 3 2 1 Input 4 0110 0001 0001 1000 3 1 2 4 Output 2 1 4 Note Below you can see the graph from the first example: <image> The given path is passing through vertexes 1, 2, 3, 4. The sequence 1-2-4 is good because it is the subsequence of the given path, its first and the last elements are equal to the first and the last elements of the given path respectively, and the shortest path passing through vertexes 1, 2 and 4 in that order is 1-2-3-4. Note that subsequences 1-4 and 1-3-4 aren't good because in both cases the shortest path passing through the vertexes of these sequences is 1-3-4. In the third example, the graph is full so any sequence of vertexes in which any two consecutive elements are distinct defines a path consisting of the same number of vertexes. In the fourth example, the paths 1-2-4 and 1-3-4 are the shortest paths passing through the vertexes 1 and 4. Submitted Solution: ``` def naiveSolve(): return def floyd_warshall(n, edges): dist = [[0 if i == j else float("inf") for i in range(n)] for j in range(n)] pred = [[None] * n for _ in range(n)] for u, v, d in edges: dist[u][v] = d pred[u][v] = u for k in range(n): for i in range(n): for j in range(n): if dist[i][k] + dist[k][j] < dist[i][j]: dist[i][j] = dist[i][k] + dist[k][j] pred[i][j] = pred[k][j] return dist, pred # #USAGE: # n=7 # edges=[[0,2,1],[2,0,1],[2,3,3],[2,4,6],[3,4,2],[4,5,1]] #[[u1,v1,d1],...] 0 <= u,v < n # ENSURE THAT u != v !!! # By default, dist[u][u] = 0 (don't need to input [u,u,0]) # dist,pred=floyd_warshall(n,edges) # # dist[u][v] is the min. dist going from u to v # # pred[u][v] is the optimal node before v when going from u to v from collections import deque def main(): # # stress test # n=100 # adj1=['1'*n for _ in range(n)] # p=[] # for _ in range(n*n): # for i in range(n): # p.append(i) # 0-indexing # m=len(p) # print(m) n=int(input()) adj1=[] for _ in range(n): adj1.append(input()) m=int(input()) p=readIntArr() for i in range(m): p[i]-=1 edges=[] for i in range(n): for j in range(n): if i==j: continue if adj1[i][j]=='1': edges.append([i,j,1]) dist,_=floyd_warshall(n,edges) # print('floyd warshall') ## q=deque() # bfs q.append(0) # node in terms of p's indexes prevNode=[-1]*m # store the prev node that visited this first (i.e. the node giving shortest dist from start) while q: node=q.popleft() for nex in range(node+1,min(m,node+101)): if prevNode[nex]!=-1: continue if nex-node==dist[p[node]][p[nex]]: # is shortest path prevNode[nex]=node q.append(nex) # print('bfs') ## pathReversed=[m-1] # in terms of p's indexes node=m-1 while node!=0: node=prevNode[node] pathReversed.append(node) path=reversed(pathReversed) ans=[p[x]+1 for x in path] print(len(ans)) oneLineArrayPrint(ans) return import sys # input=sys.stdin.buffer.readline #FOR READING PURE INTEGER INPUTS (space separation ok) input=lambda: sys.stdin.readline().rstrip("\r\n") #FOR READING STRING/TEXT INPUTS. def oneLineArrayPrint(arr): print(' '.join([str(x) for x in arr])) def multiLineArrayPrint(arr): print('\n'.join([str(x) for x in arr])) def multiLineArrayOfArraysPrint(arr): print('\n'.join([' '.join([str(x) for x in y]) for y in arr])) def readIntArr(): return [int(x) for x in input().split()] # def readFloatArr(): # return [float(x) for x in input().split()] def makeArr(defaultValFactory,dimensionArr): # eg. makeArr(lambda:0,[n,m]) dv=defaultValFactory;da=dimensionArr if len(da)==1:return [dv() for _ in range(da[0])] else:return [makeArr(dv,da[1:]) for _ in range(da[0])] def queryInteractive(i,j): print('? {} {}'.format(i,j)) sys.stdout.flush() return int(input()) def answerInteractive(ans): print('! {}'.format(' '.join([str(x) for x in ans]))) sys.stdout.flush() inf=float('inf') MOD=10**9+7 # MOD=998244353 from math import gcd,floor,ceil for _abc in range(1): main() ```
instruction
0
53,150
13
106,300
Yes
output
1
53,150
13
106,301
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The main characters have been omitted to be short. You are given a directed unweighted graph without loops with n vertexes and a path in it (that path is not necessary simple) given by a sequence p_1, p_2, …, p_m of m vertexes; for each 1 ≤ i < m there is an arc from p_i to p_{i+1}. Define the sequence v_1, v_2, …, v_k of k vertexes as good, if v is a subsequence of p, v_1 = p_1, v_k = p_m, and p is one of the shortest paths passing through the vertexes v_1, …, v_k in that order. A sequence a is a subsequence of a sequence b if a can be obtained from b by deletion of several (possibly, zero or all) elements. It is obvious that the sequence p is good but your task is to find the shortest good subsequence. If there are multiple shortest good subsequences, output any of them. Input The first line contains a single integer n (2 ≤ n ≤ 100) — the number of vertexes in a graph. The next n lines define the graph by an adjacency matrix: the j-th character in the i-st line is equal to 1 if there is an arc from vertex i to the vertex j else it is equal to 0. It is guaranteed that the graph doesn't contain loops. The next line contains a single integer m (2 ≤ m ≤ 10^6) — the number of vertexes in the path. The next line contains m integers p_1, p_2, …, p_m (1 ≤ p_i ≤ n) — the sequence of vertexes in the path. It is guaranteed that for any 1 ≤ i < m there is an arc from p_i to p_{i+1}. Output In the first line output a single integer k (2 ≤ k ≤ m) — the length of the shortest good subsequence. In the second line output k integers v_1, …, v_k (1 ≤ v_i ≤ n) — the vertexes in the subsequence. If there are multiple shortest subsequences, print any. Any two consecutive numbers should be distinct. Examples Input 4 0110 0010 0001 1000 4 1 2 3 4 Output 3 1 2 4 Input 4 0110 0010 1001 1000 20 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 Output 11 1 2 4 2 4 2 4 2 4 2 4 Input 3 011 101 110 7 1 2 3 1 3 2 1 Output 7 1 2 3 1 3 2 1 Input 4 0110 0001 0001 1000 3 1 2 4 Output 2 1 4 Note Below you can see the graph from the first example: <image> The given path is passing through vertexes 1, 2, 3, 4. The sequence 1-2-4 is good because it is the subsequence of the given path, its first and the last elements are equal to the first and the last elements of the given path respectively, and the shortest path passing through vertexes 1, 2 and 4 in that order is 1-2-3-4. Note that subsequences 1-4 and 1-3-4 aren't good because in both cases the shortest path passing through the vertexes of these sequences is 1-3-4. In the third example, the graph is full so any sequence of vertexes in which any two consecutive elements are distinct defines a path consisting of the same number of vertexes. In the fourth example, the paths 1-2-4 and 1-3-4 are the shortest paths passing through the vertexes 1 and 4. Submitted Solution: ``` import math def concat_paths(p1, p2): result = [] for pp1 in p1: for pp2 in p2: result.append(pp1 + pp2[1:]) return result def main(): n = int(input()) d = [] for i in range(n): dd = [] s = input() for j in range(n): if s[j] == '0': dd.append(False) else: dd.append(True) d.append(dd) m = int(input()) p = [int(x) for x in input().split()] dist = [] for i in range(n): ddist = [] for j in range(n): ddist.append([]) dist.append(ddist) for i in range(n): for j in range(n): if d[i][j]: dist[i][j].append([i, j]) for k in range(n): for i in range(n): if i == k: continue for j in range(n): if j == i or j == k: continue mindist = -1 if len(dist[i][j]) > 0: mindist = len(dist[i][j][0]) newdist = -1 if len(dist[i][k]) > 0 and len(dist[k][j]) > 0: newdist = len(dist[i][k][0]) + len(dist[k][j][0]) - 1 if newdist > 0: if newdist == mindist: dist[i][j] += concat_paths(dist[i][k], dist[k][j]) elif mindist < 0 or mindist > newdist: dist[i][j] = concat_paths(dist[i][k], dist[k][j]) trie = dict() for i in range(n): t = dict() for j in range(n): for path in dist[i][j]: tt = t for ind in range(1, len(path)): if path[ind] in tt: ttt = tt[path[ind]] tt = ttt else: tt[path[ind]] = dict() trie[i] = t for i in range(len(p)): p[i] -= 1 result = [p[0]] now = trie[p[0]] ind = 0 while ind < len(p): while ind + 1 < len(p) and p[ind + 1] in now: now = now[p[ind + 1]] ind += 1 result.append(p[ind]) now = trie[p[ind]] if ind == len(p) - 1: break print(len(result)) print(' '.join([str(x + 1) for x in result])) if __name__ == '__main__': main() ```
instruction
0
53,151
13
106,302
No
output
1
53,151
13
106,303
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The main characters have been omitted to be short. You are given a directed unweighted graph without loops with n vertexes and a path in it (that path is not necessary simple) given by a sequence p_1, p_2, …, p_m of m vertexes; for each 1 ≤ i < m there is an arc from p_i to p_{i+1}. Define the sequence v_1, v_2, …, v_k of k vertexes as good, if v is a subsequence of p, v_1 = p_1, v_k = p_m, and p is one of the shortest paths passing through the vertexes v_1, …, v_k in that order. A sequence a is a subsequence of a sequence b if a can be obtained from b by deletion of several (possibly, zero or all) elements. It is obvious that the sequence p is good but your task is to find the shortest good subsequence. If there are multiple shortest good subsequences, output any of them. Input The first line contains a single integer n (2 ≤ n ≤ 100) — the number of vertexes in a graph. The next n lines define the graph by an adjacency matrix: the j-th character in the i-st line is equal to 1 if there is an arc from vertex i to the vertex j else it is equal to 0. It is guaranteed that the graph doesn't contain loops. The next line contains a single integer m (2 ≤ m ≤ 10^6) — the number of vertexes in the path. The next line contains m integers p_1, p_2, …, p_m (1 ≤ p_i ≤ n) — the sequence of vertexes in the path. It is guaranteed that for any 1 ≤ i < m there is an arc from p_i to p_{i+1}. Output In the first line output a single integer k (2 ≤ k ≤ m) — the length of the shortest good subsequence. In the second line output k integers v_1, …, v_k (1 ≤ v_i ≤ n) — the vertexes in the subsequence. If there are multiple shortest subsequences, print any. Any two consecutive numbers should be distinct. Examples Input 4 0110 0010 0001 1000 4 1 2 3 4 Output 3 1 2 4 Input 4 0110 0010 1001 1000 20 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 Output 11 1 2 4 2 4 2 4 2 4 2 4 Input 3 011 101 110 7 1 2 3 1 3 2 1 Output 7 1 2 3 1 3 2 1 Input 4 0110 0001 0001 1000 3 1 2 4 Output 2 1 4 Note Below you can see the graph from the first example: <image> The given path is passing through vertexes 1, 2, 3, 4. The sequence 1-2-4 is good because it is the subsequence of the given path, its first and the last elements are equal to the first and the last elements of the given path respectively, and the shortest path passing through vertexes 1, 2 and 4 in that order is 1-2-3-4. Note that subsequences 1-4 and 1-3-4 aren't good because in both cases the shortest path passing through the vertexes of these sequences is 1-3-4. In the third example, the graph is full so any sequence of vertexes in which any two consecutive elements are distinct defines a path consisting of the same number of vertexes. In the fourth example, the paths 1-2-4 and 1-3-4 are the shortest paths passing through the vertexes 1 and 4. Submitted Solution: ``` edges = [] nodes = int(input()) for x in range(0, nodes): temp = input() temp2 = [] for y in range(0, nodes): if int(temp[y])==1: temp2.append(y+1) edges.append(temp2) pathlen = int(input()) ar = [] for t in input().split(" "): ar.append(int(t)) delnodes = [] for x in range(0, pathlen): if x+2 < pathlen: if ar[x+2] not in edges[ar[x]-1]: if ar[x+2] != ar[x]: delnodes.append(x+1) delnodes.sort(reverse=True) for y in delnodes: del ar[y] print(len(ar)) print(*ar) ```
instruction
0
53,152
13
106,304
No
output
1
53,152
13
106,305
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The main characters have been omitted to be short. You are given a directed unweighted graph without loops with n vertexes and a path in it (that path is not necessary simple) given by a sequence p_1, p_2, …, p_m of m vertexes; for each 1 ≤ i < m there is an arc from p_i to p_{i+1}. Define the sequence v_1, v_2, …, v_k of k vertexes as good, if v is a subsequence of p, v_1 = p_1, v_k = p_m, and p is one of the shortest paths passing through the vertexes v_1, …, v_k in that order. A sequence a is a subsequence of a sequence b if a can be obtained from b by deletion of several (possibly, zero or all) elements. It is obvious that the sequence p is good but your task is to find the shortest good subsequence. If there are multiple shortest good subsequences, output any of them. Input The first line contains a single integer n (2 ≤ n ≤ 100) — the number of vertexes in a graph. The next n lines define the graph by an adjacency matrix: the j-th character in the i-st line is equal to 1 if there is an arc from vertex i to the vertex j else it is equal to 0. It is guaranteed that the graph doesn't contain loops. The next line contains a single integer m (2 ≤ m ≤ 10^6) — the number of vertexes in the path. The next line contains m integers p_1, p_2, …, p_m (1 ≤ p_i ≤ n) — the sequence of vertexes in the path. It is guaranteed that for any 1 ≤ i < m there is an arc from p_i to p_{i+1}. Output In the first line output a single integer k (2 ≤ k ≤ m) — the length of the shortest good subsequence. In the second line output k integers v_1, …, v_k (1 ≤ v_i ≤ n) — the vertexes in the subsequence. If there are multiple shortest subsequences, print any. Any two consecutive numbers should be distinct. Examples Input 4 0110 0010 0001 1000 4 1 2 3 4 Output 3 1 2 4 Input 4 0110 0010 1001 1000 20 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 Output 11 1 2 4 2 4 2 4 2 4 2 4 Input 3 011 101 110 7 1 2 3 1 3 2 1 Output 7 1 2 3 1 3 2 1 Input 4 0110 0001 0001 1000 3 1 2 4 Output 2 1 4 Note Below you can see the graph from the first example: <image> The given path is passing through vertexes 1, 2, 3, 4. The sequence 1-2-4 is good because it is the subsequence of the given path, its first and the last elements are equal to the first and the last elements of the given path respectively, and the shortest path passing through vertexes 1, 2 and 4 in that order is 1-2-3-4. Note that subsequences 1-4 and 1-3-4 aren't good because in both cases the shortest path passing through the vertexes of these sequences is 1-3-4. In the third example, the graph is full so any sequence of vertexes in which any two consecutive elements are distinct defines a path consisting of the same number of vertexes. In the fourth example, the paths 1-2-4 and 1-3-4 are the shortest paths passing through the vertexes 1 and 4. Submitted Solution: ``` # TAIWAN NUMBER ONE!!!!!!!!!!!!!!!!!!! # TAIWAN NUMBER ONE!!!!!!!!!!!!!!!!!!! # TAIWAN NUMBER ONE!!!!!!!!!!!!!!!!!!! from sys import stdin, stdout from collections import defaultdict import math import copy #T = int(input()) N = int(input()) #s = input() #print(N) #N,L,R = [int(x) for x in stdin.readline().split()] #arr = [int(x) for x in stdin.readline().split()] class Graph: def __init__(self,vertices): #No. of vertices self.V = vertices self.P = 0 # default dictionary to store graph self.graph = defaultdict(list) # function to add an edge to graph def addEdge(self,u,v): self.graph[u].append(v) '''A recursive function to print all paths from 'u' to 'd'. visited[] keeps track of vertices in current path. path[] stores actual vertices and path_index is current index in path[]''' def printAllPathsUtil(self, u, d, visited): if self.P>=2: return 0 # Mark the current node as visited and store in path visited[u]= True # If current vertex is same as destination, then print # current path[] if u ==d: self.P += 1 else: # If current vertex is not destination #Recur for all the vertices adjacent to this vertex for i in self.graph[u]: if visited[i]==False: self.printAllPathsUtil(i, d, visited) # Remove current vertex from path[] and mark it as unvisited visited[u]= False # Prints all paths from 's' to 'd' def printAllPaths(self,s, d): # Mark all the vertices as not visited visited =[False]*(self.V) # Call the recursive helper function to print all paths self.printAllPathsUtil(s, d,visited) g = Graph(N) data = [] for i in range(N): s = input() data.append(s) for j in range(N): if s[j]=='1': g.addEdge(i,j) V = int(input()) arr = [int(x) for x in stdin.readline().split()] diff_paths = {} for s in range(N): for d in range(N): g.P = 0 g.printAllPaths(s,d) diff_paths[(s+1,d+1)] = g.P #print(diff_paths) # keep path = 1 start = arr[0] tmp = -1 k = 0 ans = [] for i in range(1,V-1): end = arr[i] if diff_paths[(start,end)]==1: tmp = end else: k += 1 ans.append(start) if tmp==-1: start = end else: start = tmp tmp = -1 k += 2 print(k) print(*ans,start,arr[-1]) ```
instruction
0
53,153
13
106,306
No
output
1
53,153
13
106,307
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The main characters have been omitted to be short. You are given a directed unweighted graph without loops with n vertexes and a path in it (that path is not necessary simple) given by a sequence p_1, p_2, …, p_m of m vertexes; for each 1 ≤ i < m there is an arc from p_i to p_{i+1}. Define the sequence v_1, v_2, …, v_k of k vertexes as good, if v is a subsequence of p, v_1 = p_1, v_k = p_m, and p is one of the shortest paths passing through the vertexes v_1, …, v_k in that order. A sequence a is a subsequence of a sequence b if a can be obtained from b by deletion of several (possibly, zero or all) elements. It is obvious that the sequence p is good but your task is to find the shortest good subsequence. If there are multiple shortest good subsequences, output any of them. Input The first line contains a single integer n (2 ≤ n ≤ 100) — the number of vertexes in a graph. The next n lines define the graph by an adjacency matrix: the j-th character in the i-st line is equal to 1 if there is an arc from vertex i to the vertex j else it is equal to 0. It is guaranteed that the graph doesn't contain loops. The next line contains a single integer m (2 ≤ m ≤ 10^6) — the number of vertexes in the path. The next line contains m integers p_1, p_2, …, p_m (1 ≤ p_i ≤ n) — the sequence of vertexes in the path. It is guaranteed that for any 1 ≤ i < m there is an arc from p_i to p_{i+1}. Output In the first line output a single integer k (2 ≤ k ≤ m) — the length of the shortest good subsequence. In the second line output k integers v_1, …, v_k (1 ≤ v_i ≤ n) — the vertexes in the subsequence. If there are multiple shortest subsequences, print any. Any two consecutive numbers should be distinct. Examples Input 4 0110 0010 0001 1000 4 1 2 3 4 Output 3 1 2 4 Input 4 0110 0010 1001 1000 20 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 Output 11 1 2 4 2 4 2 4 2 4 2 4 Input 3 011 101 110 7 1 2 3 1 3 2 1 Output 7 1 2 3 1 3 2 1 Input 4 0110 0001 0001 1000 3 1 2 4 Output 2 1 4 Note Below you can see the graph from the first example: <image> The given path is passing through vertexes 1, 2, 3, 4. The sequence 1-2-4 is good because it is the subsequence of the given path, its first and the last elements are equal to the first and the last elements of the given path respectively, and the shortest path passing through vertexes 1, 2 and 4 in that order is 1-2-3-4. Note that subsequences 1-4 and 1-3-4 aren't good because in both cases the shortest path passing through the vertexes of these sequences is 1-3-4. In the third example, the graph is full so any sequence of vertexes in which any two consecutive elements are distinct defines a path consisting of the same number of vertexes. In the fourth example, the paths 1-2-4 and 1-3-4 are the shortest paths passing through the vertexes 1 and 4. Submitted Solution: ``` # TAIWAN NUMBER ONE!!!!!!!!!!!!!!!!!!! # TAIWAN NUMBER ONE!!!!!!!!!!!!!!!!!!! # TAIWAN NUMBER ONE!!!!!!!!!!!!!!!!!!! from sys import stdin, stdout from collections import defaultdict import math import copy #T = int(input()) N = int(input()) #s = input() #print(N) #N,L,R = [int(x) for x in stdin.readline().split()] #arr = [int(x) for x in stdin.readline().split()] class Graph: def __init__(self,vertices): #No. of vertices self.V = vertices self.P = 0 # default dictionary to store graph self.graph = defaultdict(list) # function to add an edge to graph def addEdge(self,u,v): self.graph[u].append(v) '''A recursive function to print all paths from 'u' to 'd'. visited[] keeps track of vertices in current path. path[] stores actual vertices and path_index is current index in path[]''' def printAllPathsUtil(self, u, d, visited): if self.P>=2: return 0 # Mark the current node as visited and store in path visited[u]= True # If current vertex is same as destination, then print # current path[] if u ==d: self.P += 1 else: # If current vertex is not destination #Recur for all the vertices adjacent to this vertex for i in self.graph[u]: if visited[i]==False: self.printAllPathsUtil(i, d, visited) # Remove current vertex from path[] and mark it as unvisited visited[u]= False # Prints all paths from 's' to 'd' def printAllPaths(self,s, d): # Mark all the vertices as not visited visited =[False]*(self.V) # Call the recursive helper function to print all paths self.printAllPathsUtil(s, d,visited) g = Graph(N) data = [] for i in range(N): s = input() data.append(s) for j in range(N): if s[j]=='1': g.addEdge(i,j) V = int(input()) arr = [int(x) for x in stdin.readline().split()] diff_paths = {} for s in range(N): for d in range(N): g.P = 0 g.printAllPaths(s,d) diff_paths[(s+1,d+1)] = g.P #print(diff_paths) # keep path = 1 start = arr[0] tmp = -1 k = 0 ans = [] for i in range(1,V): end = arr[i] if diff_paths[(start,end)]==1: tmp = end else: k += 1 ans.append(start) if tmp==-1: start = end else: start = tmp tmp = -1 k += 2 print(k) print(*ans,start,arr[-1]) ```
instruction
0
53,154
13
106,308
No
output
1
53,154
13
106,309
Provide tags and a correct Python 3 solution for this coding contest problem. Evlampiy was gifted a rooted tree. The vertices of the tree are numbered from 1 to n. Each of its vertices also has an integer a_i written on it. For each vertex i, Evlampiy calculated c_i — the number of vertices j in the subtree of vertex i, such that a_j < a_i. <image>Illustration for the second example, the first integer is a_i and the integer in parentheses is c_i After the new year, Evlampiy could not remember what his gift was! He remembers the tree and the values of c_i, but he completely forgot which integers a_i were written on the vertices. Help him to restore initial integers! Input The first line contains an integer n (1 ≤ n ≤ 2000) — the number of vertices in the tree. The next n lines contain descriptions of vertices: the i-th line contains two integers p_i and c_i (0 ≤ p_i ≤ n; 0 ≤ c_i ≤ n-1), where p_i is the parent of vertex i or 0 if vertex i is root, and c_i is the number of vertices j in the subtree of vertex i, such that a_j < a_i. It is guaranteed that the values of p_i describe a rooted tree with n vertices. Output If a solution exists, in the first line print "YES", and in the second line output n integers a_i (1 ≤ a_i ≤ {10}^{9}). If there are several solutions, output any of them. One can prove that if there is a solution, then there is also a solution in which all a_i are between 1 and 10^9. If there are no solutions, print "NO". Examples Input 3 2 0 0 2 2 0 Output YES 1 2 1 Input 5 0 1 1 3 2 1 3 0 2 0 Output YES 2 3 2 1 2
instruction
0
53,187
13
106,374
Tags: constructive algorithms, data structures, dfs and similar, graphs, greedy, trees Correct Solution: ``` import sys # inf = open('input.txt', 'r') # reader = (line.rstrip() for line in inf) reader = (line.rstrip() for line in sys.stdin) input = reader.__next__ n = int(input()) cs = [0] * (n + 1) ps = [0] * (n + 1) children = [[] for _ in range(n+1)] for i in range(1, n+1): p, c = map(int, input().split()) ps[i] = p children[p].append(i) cs[i] = c def sortDescendants(v): result = [] pos = cs[v] for child in children[v]: result += sortDescendants(child) if len(result) < pos: print('NO') sys.exit() result.insert(pos, v) return result root = children[0][0] order = sortDescendants(root) a = [0] * n for i, v in enumerate(order): a[v - 1] = i + 1 print('YES') print(*a) # inf.close() ```
output
1
53,187
13
106,375
Provide tags and a correct Python 3 solution for this coding contest problem. Evlampiy was gifted a rooted tree. The vertices of the tree are numbered from 1 to n. Each of its vertices also has an integer a_i written on it. For each vertex i, Evlampiy calculated c_i — the number of vertices j in the subtree of vertex i, such that a_j < a_i. <image>Illustration for the second example, the first integer is a_i and the integer in parentheses is c_i After the new year, Evlampiy could not remember what his gift was! He remembers the tree and the values of c_i, but he completely forgot which integers a_i were written on the vertices. Help him to restore initial integers! Input The first line contains an integer n (1 ≤ n ≤ 2000) — the number of vertices in the tree. The next n lines contain descriptions of vertices: the i-th line contains two integers p_i and c_i (0 ≤ p_i ≤ n; 0 ≤ c_i ≤ n-1), where p_i is the parent of vertex i or 0 if vertex i is root, and c_i is the number of vertices j in the subtree of vertex i, such that a_j < a_i. It is guaranteed that the values of p_i describe a rooted tree with n vertices. Output If a solution exists, in the first line print "YES", and in the second line output n integers a_i (1 ≤ a_i ≤ {10}^{9}). If there are several solutions, output any of them. One can prove that if there is a solution, then there is also a solution in which all a_i are between 1 and 10^9. If there are no solutions, print "NO". Examples Input 3 2 0 0 2 2 0 Output YES 1 2 1 Input 5 0 1 1 3 2 1 3 0 2 0 Output YES 2 3 2 1 2
instruction
0
53,188
13
106,376
Tags: constructive algorithms, data structures, dfs and similar, graphs, greedy, trees Correct Solution: ``` import sys # BIT aka Fenwick tree # sum class BIT(): def __init__(self, n): self.n = n self.tree = [0] * n def _F(self, i): return i & (i + 1) def _getSum(self, r): ''' sum on interval [0, r] ''' result = 0 while r >= 0: result += self.tree[r] r = self._F(r) - 1 return result def getSum(self, l, r): ''' sum on interval [l, r] ''' return self._getSum(r) - self._getSum(l - 1) def _H(self, i): return i | (i + 1) def add(self, i, value=1): while i < self.n: self.tree[i] += value i = self._H(i) # inf = open('input.txt', 'r') # reader = (line.rstrip() for line in inf) reader = (line.rstrip() for line in sys.stdin) input = reader.__next__ n = int(input()) cs = [0] * n ps = [0] * n children = [[] for _ in range(n)] for i in range(n): p, c = map(int, input().split()) if p > 0: ps[i] = p - 1 children[p - 1].append(i) else: root = i cs[i] = c # inf.close() visited = [False] * n stack = [root] prev = -1 rank = [1] * n while stack: v = stack.pop() if not visited[v]: visited[v] = True for to in children[v]: stack.append(v) stack.append(to) else: rank[v] += rank[prev] prev = v # print(rank) unused = BIT(n) for i in range(n): unused.add(i) ans = [None] * n stack = [root] while stack: v = stack.pop() kth = cs[v] + 1 if kth > rank[v]: print('NO') sys.exit() L = -1 R = n-1 while L + 1 < R: m = (L + R) >> 1 if unused.getSum(0, m) < kth: L = m else: R = m ans[v] = R + 1 unused.add(R, -1) stack.extend(children[v]) print('YES') print(*ans) ```
output
1
53,188
13
106,377
Provide tags and a correct Python 3 solution for this coding contest problem. Evlampiy was gifted a rooted tree. The vertices of the tree are numbered from 1 to n. Each of its vertices also has an integer a_i written on it. For each vertex i, Evlampiy calculated c_i — the number of vertices j in the subtree of vertex i, such that a_j < a_i. <image>Illustration for the second example, the first integer is a_i and the integer in parentheses is c_i After the new year, Evlampiy could not remember what his gift was! He remembers the tree and the values of c_i, but he completely forgot which integers a_i were written on the vertices. Help him to restore initial integers! Input The first line contains an integer n (1 ≤ n ≤ 2000) — the number of vertices in the tree. The next n lines contain descriptions of vertices: the i-th line contains two integers p_i and c_i (0 ≤ p_i ≤ n; 0 ≤ c_i ≤ n-1), where p_i is the parent of vertex i or 0 if vertex i is root, and c_i is the number of vertices j in the subtree of vertex i, such that a_j < a_i. It is guaranteed that the values of p_i describe a rooted tree with n vertices. Output If a solution exists, in the first line print "YES", and in the second line output n integers a_i (1 ≤ a_i ≤ {10}^{9}). If there are several solutions, output any of them. One can prove that if there is a solution, then there is also a solution in which all a_i are between 1 and 10^9. If there are no solutions, print "NO". Examples Input 3 2 0 0 2 2 0 Output YES 1 2 1 Input 5 0 1 1 3 2 1 3 0 2 0 Output YES 2 3 2 1 2
instruction
0
53,189
13
106,378
Tags: constructive algorithms, data structures, dfs and similar, graphs, greedy, trees Correct Solution: ``` from bisect import bisect_left as bl from bisect import bisect_right as br import heapq import math from collections import * from functools import reduce,cmp_to_key import sys input = sys.stdin.readline # M = mod = 998244353 def factors(n):return sorted(list(set(reduce(list.__add__,([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0))))) # def inv_mod(n):return pow(n, mod - 2, mod) def li():return [int(i) for i in input().rstrip('\n').split(' ')] def st():return input().rstrip('\n') def val():return int(input().rstrip('\n')) def li2():return [i for i in input().rstrip('\n').split(' ')] def li3():return [int(i) for i in input().rstrip('\n')] va = 10**7 helpl = defaultdict(deque) def dfs(i): global va curr = [] # print('currnode : ',i) for j in d[i]: curr.extend(dfs(j)) curr = sorted(list(curr)) # print('currlen : ',curr,'c value : ',c[i-1]) if len(curr) < c[i-1]: print('NO') exit() if not len(curr): curr.append(va) helpl[va].append(i-1) va -= 2000 else: # if c[i-1] == 0: # # curr.append(curr[0] - 1) # helpl[curr[0]].append(i-1) # print(curr) for j in range(c[i-1]): helpl[curr[j] - 1].append(helpl[curr[j]].popleft()) curr[j] -= 1 for j in range(len(curr)-1,c[i-1]-1,-1): helpl[curr[j] + 1].append(helpl[curr[j]].popleft()) helpl[curr[j]] = deque() curr[j] += 1 # print(curr,c[i-1]) if c[i-1] == len(curr):curr.append(curr[-1] + 1) else:curr = curr[:c[i-1]] + [curr[c[i-1]]-1] + curr[c[i-1]:] helpl[curr[c[i-1]]].append(i-1) # print(helpl) # for i in helpl: # if len(helpl[i]): # helpl[i] = deque(sorted(helpl[i])) return curr n = val() d = defaultdict(list) c = [] a = [0 for i in range(n)] for i in range(n): x,y = li() d[x].append(i + 1) c.append(y) # print(d) root = d[0][0] d.pop(0) for i in d: d[i] = sorted(d[i]) # print(d,c,root) dfs(root) curr = 1 # print(helpl) for i in sorted(helpl): # print(i) for j in helpl[i]: a[j] = curr if len(helpl[i]):curr += 1 print('YES') print(*a) ```
output
1
53,189
13
106,379
Provide tags and a correct Python 3 solution for this coding contest problem. Evlampiy was gifted a rooted tree. The vertices of the tree are numbered from 1 to n. Each of its vertices also has an integer a_i written on it. For each vertex i, Evlampiy calculated c_i — the number of vertices j in the subtree of vertex i, such that a_j < a_i. <image>Illustration for the second example, the first integer is a_i and the integer in parentheses is c_i After the new year, Evlampiy could not remember what his gift was! He remembers the tree and the values of c_i, but he completely forgot which integers a_i were written on the vertices. Help him to restore initial integers! Input The first line contains an integer n (1 ≤ n ≤ 2000) — the number of vertices in the tree. The next n lines contain descriptions of vertices: the i-th line contains two integers p_i and c_i (0 ≤ p_i ≤ n; 0 ≤ c_i ≤ n-1), where p_i is the parent of vertex i or 0 if vertex i is root, and c_i is the number of vertices j in the subtree of vertex i, such that a_j < a_i. It is guaranteed that the values of p_i describe a rooted tree with n vertices. Output If a solution exists, in the first line print "YES", and in the second line output n integers a_i (1 ≤ a_i ≤ {10}^{9}). If there are several solutions, output any of them. One can prove that if there is a solution, then there is also a solution in which all a_i are between 1 and 10^9. If there are no solutions, print "NO". Examples Input 3 2 0 0 2 2 0 Output YES 1 2 1 Input 5 0 1 1 3 2 1 3 0 2 0 Output YES 2 3 2 1 2
instruction
0
53,190
13
106,380
Tags: constructive algorithms, data structures, dfs and similar, graphs, greedy, trees Correct Solution: ``` #!usr/bin/env python3 from collections import defaultdict,deque from heapq import heappush, heappop from itertools import permutations import sys import math import bisect import random def LI(): return [int(x) for x in sys.stdin.readline().split()] def I(): return int(sys.stdin.readline()) def LS():return [list(x) for x in sys.stdin.readline().split()] def S(): res = list(sys.stdin.readline()) if res[-1] == "\n": return res[:-1] return res def IR(n): return [I() for i in range(n)] def LIR(n): return [LI() for i in range(n)] def SR(n): return [S() for i in range(n)] def LSR(n): return [LS() for i in range(n)] sys.setrecursionlimit(1000000) mod = 1000000007 def solve(): def dfs(x): size[x] = 1 for y in v[x]: size[x] += dfs(y) return size[x] def dfs2(x): cx = c[x] ans[x] = f[cx] f.pop(cx) for y in v[x]: dfs2(y) n = I() v = [[] for i in range(n)] c = [0]*n f = [[0,i] for i in range(n)] r = None for i in range(n): a,b = LI() a -= 1 if a >= 0: f[a][0] += 1 v[a].append(i) else: r = i c[i] = b size = [0]*n dfs(r) f = [i+1 for i in range(n)] for i in range(n): if c[i] >= size[i]: print("NO") return ans = [0]*n dfs2(r) print("YES") print(*ans) return #Solve if __name__ == "__main__": solve() ```
output
1
53,190
13
106,381
Provide tags and a correct Python 3 solution for this coding contest problem. Evlampiy was gifted a rooted tree. The vertices of the tree are numbered from 1 to n. Each of its vertices also has an integer a_i written on it. For each vertex i, Evlampiy calculated c_i — the number of vertices j in the subtree of vertex i, such that a_j < a_i. <image>Illustration for the second example, the first integer is a_i and the integer in parentheses is c_i After the new year, Evlampiy could not remember what his gift was! He remembers the tree and the values of c_i, but he completely forgot which integers a_i were written on the vertices. Help him to restore initial integers! Input The first line contains an integer n (1 ≤ n ≤ 2000) — the number of vertices in the tree. The next n lines contain descriptions of vertices: the i-th line contains two integers p_i and c_i (0 ≤ p_i ≤ n; 0 ≤ c_i ≤ n-1), where p_i is the parent of vertex i or 0 if vertex i is root, and c_i is the number of vertices j in the subtree of vertex i, such that a_j < a_i. It is guaranteed that the values of p_i describe a rooted tree with n vertices. Output If a solution exists, in the first line print "YES", and in the second line output n integers a_i (1 ≤ a_i ≤ {10}^{9}). If there are several solutions, output any of them. One can prove that if there is a solution, then there is also a solution in which all a_i are between 1 and 10^9. If there are no solutions, print "NO". Examples Input 3 2 0 0 2 2 0 Output YES 1 2 1 Input 5 0 1 1 3 2 1 3 0 2 0 Output YES 2 3 2 1 2
instruction
0
53,191
13
106,382
Tags: constructive algorithms, data structures, dfs and similar, graphs, greedy, trees Correct Solution: ``` import sys # BIT aka Fenwick tree # sum class BIT(): def __init__(self, n): self.n = n self.tree = [0] * n def _F(self, i): return i & (i + 1) def _getSum(self, r): ''' sum on interval [0, r] ''' result = 0 while r >= 0: result += self.tree[r] r = self._F(r) - 1 return result def getSum(self, l, r): ''' sum on interval [l, r] ''' return self._getSum(r) - self._getSum(l - 1) def _H(self, i): return i | (i + 1) def add(self, i, value=1): while i < self.n: self.tree[i] += value i = self._H(i) # inf = open('input.txt', 'r') # reader = (line.rstrip() for line in inf) reader = (line.rstrip() for line in sys.stdin) input = reader.__next__ n = int(input()) # n = 5 * 10 ** 5 cs = [0] * n ps = [0] * n children = [[] for _ in range(n)] for i in range(n): p, c = map(int, input().split()) # p, c = i, 0 if p > 0: ps[i] = p - 1 children[p - 1].append(i) else: root = i cs[i] = c # inf.close() visited = [False] * n stack = [root] prev = -1 rank = [1] * n while stack: v = stack.pop() if not visited[v]: visited[v] = True for to in children[v]: stack.append(v) stack.append(to) else: rank[v] += rank[prev] prev = v # print(rank) used = BIT(n) ans = [None] * n stack = [root] while stack: v = stack.pop() kth = cs[v] + 1 if kth > rank[v]: print('NO') sys.exit() L = -1 R = n-1 while L + 1 < R: m = (L + R) >> 1 if m + 1 - used.getSum(0, m) < kth: L = m else: R = m ans[v] = R + 1 used.add(R) stack.extend(children[v]) print('YES') print(*ans) ```
output
1
53,191
13
106,383
Provide tags and a correct Python 3 solution for this coding contest problem. Evlampiy was gifted a rooted tree. The vertices of the tree are numbered from 1 to n. Each of its vertices also has an integer a_i written on it. For each vertex i, Evlampiy calculated c_i — the number of vertices j in the subtree of vertex i, such that a_j < a_i. <image>Illustration for the second example, the first integer is a_i and the integer in parentheses is c_i After the new year, Evlampiy could not remember what his gift was! He remembers the tree and the values of c_i, but he completely forgot which integers a_i were written on the vertices. Help him to restore initial integers! Input The first line contains an integer n (1 ≤ n ≤ 2000) — the number of vertices in the tree. The next n lines contain descriptions of vertices: the i-th line contains two integers p_i and c_i (0 ≤ p_i ≤ n; 0 ≤ c_i ≤ n-1), where p_i is the parent of vertex i or 0 if vertex i is root, and c_i is the number of vertices j in the subtree of vertex i, such that a_j < a_i. It is guaranteed that the values of p_i describe a rooted tree with n vertices. Output If a solution exists, in the first line print "YES", and in the second line output n integers a_i (1 ≤ a_i ≤ {10}^{9}). If there are several solutions, output any of them. One can prove that if there is a solution, then there is also a solution in which all a_i are between 1 and 10^9. If there are no solutions, print "NO". Examples Input 3 2 0 0 2 2 0 Output YES 1 2 1 Input 5 0 1 1 3 2 1 3 0 2 0 Output YES 2 3 2 1 2
instruction
0
53,192
13
106,384
Tags: constructive algorithms, data structures, dfs and similar, graphs, greedy, trees Correct Solution: ``` from sys import setrecursionlimit setrecursionlimit(1000000) n = int(input()) graph = [[] for _ in range(n + 1)] ci = [0] def solve(x): rlt = [] for v in graph[x]: rlt.extend(solve(v)) if len(rlt) < ci[x]: raise ValueError rlt.insert(ci[x], x) return rlt for i in range(1, n + 1): p, c = map(int, input().split()) graph[p].append(i) ci.append(c) try: ans = solve(graph[0][0]) except ValueError: print("NO") else: print("YES") for i in range(1, n + 1): print(ans.index(i) + 1, end=' ') ```
output
1
53,192
13
106,385
Provide tags and a correct Python 3 solution for this coding contest problem. Evlampiy was gifted a rooted tree. The vertices of the tree are numbered from 1 to n. Each of its vertices also has an integer a_i written on it. For each vertex i, Evlampiy calculated c_i — the number of vertices j in the subtree of vertex i, such that a_j < a_i. <image>Illustration for the second example, the first integer is a_i and the integer in parentheses is c_i After the new year, Evlampiy could not remember what his gift was! He remembers the tree and the values of c_i, but he completely forgot which integers a_i were written on the vertices. Help him to restore initial integers! Input The first line contains an integer n (1 ≤ n ≤ 2000) — the number of vertices in the tree. The next n lines contain descriptions of vertices: the i-th line contains two integers p_i and c_i (0 ≤ p_i ≤ n; 0 ≤ c_i ≤ n-1), where p_i is the parent of vertex i or 0 if vertex i is root, and c_i is the number of vertices j in the subtree of vertex i, such that a_j < a_i. It is guaranteed that the values of p_i describe a rooted tree with n vertices. Output If a solution exists, in the first line print "YES", and in the second line output n integers a_i (1 ≤ a_i ≤ {10}^{9}). If there are several solutions, output any of them. One can prove that if there is a solution, then there is also a solution in which all a_i are between 1 and 10^9. If there are no solutions, print "NO". Examples Input 3 2 0 0 2 2 0 Output YES 1 2 1 Input 5 0 1 1 3 2 1 3 0 2 0 Output YES 2 3 2 1 2
instruction
0
53,193
13
106,386
Tags: constructive algorithms, data structures, dfs and similar, graphs, greedy, trees Correct Solution: ``` from sys import stdin, stdout import math from bisect import bisect_left, bisect_right input = lambda: stdin.readline().strip() print = lambda s: stdout.write(s) n = int(input()) children = {} for i in range(n): children[i] = [] c = [] for i in range(n): a, b = map(int, input().split()) if a!=0: children[a-1].append(i) else: r = i c.append(b) def sortTree(root): ls = [] for i in children[root]: ls+=sortTree(i) if c[root]<=len(ls): ls.insert(c[root], root) else: print('NO') exit() return ls ls1 = sortTree(r) ans = {} for i in range(n): ans[ls1[i]] = i+1 print('YES\n') for i in range(n): print(str(ans[i])+' ') print('\n') ```
output
1
53,193
13
106,387
Provide tags and a correct Python 3 solution for this coding contest problem. Evlampiy was gifted a rooted tree. The vertices of the tree are numbered from 1 to n. Each of its vertices also has an integer a_i written on it. For each vertex i, Evlampiy calculated c_i — the number of vertices j in the subtree of vertex i, such that a_j < a_i. <image>Illustration for the second example, the first integer is a_i and the integer in parentheses is c_i After the new year, Evlampiy could not remember what his gift was! He remembers the tree and the values of c_i, but he completely forgot which integers a_i were written on the vertices. Help him to restore initial integers! Input The first line contains an integer n (1 ≤ n ≤ 2000) — the number of vertices in the tree. The next n lines contain descriptions of vertices: the i-th line contains two integers p_i and c_i (0 ≤ p_i ≤ n; 0 ≤ c_i ≤ n-1), where p_i is the parent of vertex i or 0 if vertex i is root, and c_i is the number of vertices j in the subtree of vertex i, such that a_j < a_i. It is guaranteed that the values of p_i describe a rooted tree with n vertices. Output If a solution exists, in the first line print "YES", and in the second line output n integers a_i (1 ≤ a_i ≤ {10}^{9}). If there are several solutions, output any of them. One can prove that if there is a solution, then there is also a solution in which all a_i are between 1 and 10^9. If there are no solutions, print "NO". Examples Input 3 2 0 0 2 2 0 Output YES 1 2 1 Input 5 0 1 1 3 2 1 3 0 2 0 Output YES 2 3 2 1 2
instruction
0
53,194
13
106,388
Tags: constructive algorithms, data structures, dfs and similar, graphs, greedy, trees Correct Solution: ``` n = int(input()) adj_list = [[] for i in range(n + 1)] c = [None] for i in range(1, n + 1): p_i, c_i = map(int, input().split()) c.append(c_i) adj_list[p_i].append(i) sizes = [None for i in range(n + 1)] values = [None for i in range(n + 1)] def size(v): sizes[v] = 1 for i in adj_list[v]: size(i) sizes[v] += sizes[i] size(adj_list[0][0]) #print(adj_list) def get_ans(v): if len(adj_list[v]) == 0: if c[v] != 0: return None return [[1, v]] insert_at = c[v] merged_list = [] current_size = 0 for child in adj_list[v]: ans = get_ans(child) if ans == None: return None merged_list += [[x[0] + current_size, x[1]] for x in ans] current_size += sizes[child] #print(merged_list) if insert_at > len(merged_list) or insert_at < 0: return None new_list = merged_list[:insert_at] new_list.append([insert_at + 1, v]) new_list += [[x[0] + 1, x[1]] for x in merged_list[insert_at:]] #print(new_list) return new_list x = get_ans(adj_list[0][0]) if x == None: print("NO") else: print("YES") #print(x) x.sort(key = lambda i: i[1]) x = [str(a[0]) for a in x] print(" ".join(x)) ```
output
1
53,194
13
106,389
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Evlampiy was gifted a rooted tree. The vertices of the tree are numbered from 1 to n. Each of its vertices also has an integer a_i written on it. For each vertex i, Evlampiy calculated c_i — the number of vertices j in the subtree of vertex i, such that a_j < a_i. <image>Illustration for the second example, the first integer is a_i and the integer in parentheses is c_i After the new year, Evlampiy could not remember what his gift was! He remembers the tree and the values of c_i, but he completely forgot which integers a_i were written on the vertices. Help him to restore initial integers! Input The first line contains an integer n (1 ≤ n ≤ 2000) — the number of vertices in the tree. The next n lines contain descriptions of vertices: the i-th line contains two integers p_i and c_i (0 ≤ p_i ≤ n; 0 ≤ c_i ≤ n-1), where p_i is the parent of vertex i or 0 if vertex i is root, and c_i is the number of vertices j in the subtree of vertex i, such that a_j < a_i. It is guaranteed that the values of p_i describe a rooted tree with n vertices. Output If a solution exists, in the first line print "YES", and in the second line output n integers a_i (1 ≤ a_i ≤ {10}^{9}). If there are several solutions, output any of them. One can prove that if there is a solution, then there is also a solution in which all a_i are between 1 and 10^9. If there are no solutions, print "NO". Examples Input 3 2 0 0 2 2 0 Output YES 1 2 1 Input 5 0 1 1 3 2 1 3 0 2 0 Output YES 2 3 2 1 2 Submitted Solution: ``` import sys class SegmTree(): def __init__(self, array=None, size=None): if array is not None: size = len(array) N = 1 while N < size: N <<= 1 self.N = N self.tree = [0] * (2*self.N) if array is not None: for i in range(size): self.tree[i+self.N] = array[i] self.build() def build(self): for i in range(self.N - 1, 0, -1): self.tree[i] = self.tree[i<<1] + self.tree[i<<1|1] def add(self, i, value=1): i += self.N while i > 0: self.tree[i] += value i >>= 1 def find_kth_nonzero(self, k): i = 1 if k < 1 or k > self.tree[1]: return -1 while i < self.N: i <<= 1 if self.tree[i] < k: k -= self.tree[i] i |= 1 return i - self.N # inf = open('input.txt', 'r') # reader = (line.rstrip() for line in inf) reader = (line.rstrip() for line in sys.stdin) input = reader.__next__ n = int(input()) # n = 5 * 10 ** 5 cs = [0] * n ps = [0] * n children = [[] for _ in range(n)] for i in range(n): p, c = map(int, input().split()) # p, c = i, 0 if p > 0: ps[i] = p - 1 children[p - 1].append(i) else: root = i cs[i] = c # inf.close() visited = [False] * n stack = [root] prev = -1 rank = [1] * n while stack: v = stack.pop() if not visited[v]: visited[v] = True for to in children[v]: stack.append(v) stack.append(to) else: rank[v] += rank[prev] prev = v unused = SegmTree([1] * n) ans = [None] * n stack = [root] while stack: v = stack.pop() k = cs[v] + 1 if k > rank[v]: print('NO') sys.exit() i = unused.find_kth_nonzero(k) ans[v] = i + 1 unused.add(i, -1) stack.extend(children[v]) print('YES') print(*ans) ```
instruction
0
53,195
13
106,390
Yes
output
1
53,195
13
106,391
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Evlampiy was gifted a rooted tree. The vertices of the tree are numbered from 1 to n. Each of its vertices also has an integer a_i written on it. For each vertex i, Evlampiy calculated c_i — the number of vertices j in the subtree of vertex i, such that a_j < a_i. <image>Illustration for the second example, the first integer is a_i and the integer in parentheses is c_i After the new year, Evlampiy could not remember what his gift was! He remembers the tree and the values of c_i, but he completely forgot which integers a_i were written on the vertices. Help him to restore initial integers! Input The first line contains an integer n (1 ≤ n ≤ 2000) — the number of vertices in the tree. The next n lines contain descriptions of vertices: the i-th line contains two integers p_i and c_i (0 ≤ p_i ≤ n; 0 ≤ c_i ≤ n-1), where p_i is the parent of vertex i or 0 if vertex i is root, and c_i is the number of vertices j in the subtree of vertex i, such that a_j < a_i. It is guaranteed that the values of p_i describe a rooted tree with n vertices. Output If a solution exists, in the first line print "YES", and in the second line output n integers a_i (1 ≤ a_i ≤ {10}^{9}). If there are several solutions, output any of them. One can prove that if there is a solution, then there is also a solution in which all a_i are between 1 and 10^9. If there are no solutions, print "NO". Examples Input 3 2 0 0 2 2 0 Output YES 1 2 1 Input 5 0 1 1 3 2 1 3 0 2 0 Output YES 2 3 2 1 2 Submitted Solution: ``` """ Author - Satwik Tiwari . 5th Jan , 2021 - Tuesday """ #=============================================================================================== #importing some useful libraries. from __future__ import division, print_function from fractions import Fraction import sys import os from io import BytesIO, IOBase from functools import cmp_to_key # from itertools import * from heapq import * from math import gcd, factorial,floor,ceil,sqrt from copy import deepcopy from collections import deque from bisect import bisect_left as bl from bisect import bisect_right as br from bisect import bisect #============================================================================================== #fast I/O region 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") def print(*args, **kwargs): """Prints the values to a stream, or to sys.stdout by default.""" sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout) at_start = True for x in args: if not at_start: file.write(sep) file.write(str(x)) at_start = False file.write(kwargs.pop("end", "\n")) if kwargs.pop("flush", False): file.flush() if sys.version_info[0] < 3: sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout) else: sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) # inp = lambda: sys.stdin.readline().rstrip("\r\n") #=============================================================================================== ### START ITERATE RECURSION ### from types import GeneratorType def iterative(f, stack=[]): def wrapped_func(*args, **kwargs): if stack: return f(*args, **kwargs) to = f(*args, **kwargs) while True: if type(to) is GeneratorType: stack.append(to) to = next(to) continue stack.pop() if not stack: break to = stack[-1].send(to) return to return wrapped_func #### END ITERATE RECURSION #### #=============================================================================================== #some shortcuts def inp(): return sys.stdin.readline().rstrip("\r\n") #for fast input def out(var): sys.stdout.write(str(var)) #for fast output, always take string def lis(): return list(map(int, inp().split())) def stringlis(): return list(map(str, inp().split())) def sep(): return map(int, inp().split()) def strsep(): return map(str, inp().split()) # def graph(vertex): return [[] for i in range(0,vertex+1)] def testcase(t): for pp in range(t): solve(pp) def google(p): print('Case #'+str(p)+': ',end='') def lcm(a,b): return (a*b)//gcd(a,b) def power(x, y, p) : y%=(p-1) #not so sure about this. used when y>p-1. if p is prime. res = 1 # Initialize result x = x % p # Update x if it is more , than or equal to p if (x == 0) : return 0 while (y > 0) : if ((y & 1) == 1) : # If y is odd, multiply, x with result res = (res * x) % p y = y >> 1 # y = y/2 x = (x * x) % p return res def ncr(n,r): return factorial(n) // (factorial(r) * factorial(max(n - r, 1))) def isPrime(n) : if (n <= 1) : return False if (n <= 3) : return True if (n % 2 == 0 or n % 3 == 0) : return False i = 5 while(i * i <= n) : if (n % i == 0 or n % (i + 2) == 0) : return False i = i + 6 return True inf = pow(10,20) mod = 10**9+7 #=============================================================================================== # code here ;)) @iterative def dfs(v,visited,st): visited[st] = 1 for i in v[st]: if(visited[i] == 0): ok = yield dfs(v,visited,i) sub[st] += sub[i] yield True @iterative def dfs2(v,visited,st): visited[st] = 1 arr = [] global root for i in v[st]: if(visited[i] == 0): ok = yield dfs2(v,visited,i) arr += ok if(len(v[st]) == 1 and st != root): arr.append([1,st]) else: arr = sorted(arr) if(c[st] == 0): for i in range(len(arr)): arr[i][0] += 1 arr.append([1,st]) elif(c[st] >= len(arr)): arr.append([arr[-1][0] + 1,st]) else: for i in range(c[st],len(arr)): arr[i][0] += 2 arr.append([arr[c[st]-1][0]+1,st]) yield arr def solve(case): n = int(inp()) g = [[] for i in range(n)] global root for i in range(n): a,b = sep() if(a != 0): a-=1 g[a].append(i) g[i].append(a) else: root = i c.append(b) vis = [0]*n dfs(g,vis,root) # print(g) # print(sub) # print(c) for i in range(n): if(sub[i]-1 < c[i]): print("NO") return print('YES') vis = [0]*n ans = dfs2(g,vis,root) out = [0]*n for i,j in ans: out[j] = i print(' '.join(str(out[i]) for i in range(n))) root = 0 sub = [1]*(2020) c = [] testcase(1) # testcase(int(inp())) ```
instruction
0
53,196
13
106,392
Yes
output
1
53,196
13
106,393
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Evlampiy was gifted a rooted tree. The vertices of the tree are numbered from 1 to n. Each of its vertices also has an integer a_i written on it. For each vertex i, Evlampiy calculated c_i — the number of vertices j in the subtree of vertex i, such that a_j < a_i. <image>Illustration for the second example, the first integer is a_i and the integer in parentheses is c_i After the new year, Evlampiy could not remember what his gift was! He remembers the tree and the values of c_i, but he completely forgot which integers a_i were written on the vertices. Help him to restore initial integers! Input The first line contains an integer n (1 ≤ n ≤ 2000) — the number of vertices in the tree. The next n lines contain descriptions of vertices: the i-th line contains two integers p_i and c_i (0 ≤ p_i ≤ n; 0 ≤ c_i ≤ n-1), where p_i is the parent of vertex i or 0 if vertex i is root, and c_i is the number of vertices j in the subtree of vertex i, such that a_j < a_i. It is guaranteed that the values of p_i describe a rooted tree with n vertices. Output If a solution exists, in the first line print "YES", and in the second line output n integers a_i (1 ≤ a_i ≤ {10}^{9}). If there are several solutions, output any of them. One can prove that if there is a solution, then there is also a solution in which all a_i are between 1 and 10^9. If there are no solutions, print "NO". Examples Input 3 2 0 0 2 2 0 Output YES 1 2 1 Input 5 0 1 1 3 2 1 3 0 2 0 Output YES 2 3 2 1 2 Submitted Solution: ``` # https://codeforces.com/contest/1287/problem/D def push(g, u, v): if u not in g: g[u] = [] g[u].append(v) def build(): S = [root] i = 0 order = {} while i < len(S): u = S[i] if u in g: for v in g[u]: S.append(v) i+=1 for u in S[::-1]: order[u] = [] flg=False if u not in g: if cnt[u]==0: order[u].append(u) flg=True else: return False, root, order else: cur = 0 for v in g[u]: for x in order[v]: if cur==cnt[u]: flg=True order[u].append(u) cur+=1 order[u].append(x) cur+=1 if flg == False: if cnt[u] > len(order[u]): return False, root, order else: order[u].append(u) return True, root, order n = int(input()) g = {} cnt = {} for i in range(1, n+1): p, c = map(int, input().split()) cnt[i] = c if p==0: root = i else: push(g, p, i) flg, root, order = build() if flg==False: print('NO') else: ans = [-1] * n for val, u in zip(list(range(n)), order[root]): ans[u-1] = val + 1 print('YES') print(' '.join([str(x) for x in ans])) #5 #0 1 #1 3 #2 1 #3 0 #2 0 #3 #2 0 #0 2 #2 0 ```
instruction
0
53,197
13
106,394
Yes
output
1
53,197
13
106,395
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Evlampiy was gifted a rooted tree. The vertices of the tree are numbered from 1 to n. Each of its vertices also has an integer a_i written on it. For each vertex i, Evlampiy calculated c_i — the number of vertices j in the subtree of vertex i, such that a_j < a_i. <image>Illustration for the second example, the first integer is a_i and the integer in parentheses is c_i After the new year, Evlampiy could not remember what his gift was! He remembers the tree and the values of c_i, but he completely forgot which integers a_i were written on the vertices. Help him to restore initial integers! Input The first line contains an integer n (1 ≤ n ≤ 2000) — the number of vertices in the tree. The next n lines contain descriptions of vertices: the i-th line contains two integers p_i and c_i (0 ≤ p_i ≤ n; 0 ≤ c_i ≤ n-1), where p_i is the parent of vertex i or 0 if vertex i is root, and c_i is the number of vertices j in the subtree of vertex i, such that a_j < a_i. It is guaranteed that the values of p_i describe a rooted tree with n vertices. Output If a solution exists, in the first line print "YES", and in the second line output n integers a_i (1 ≤ a_i ≤ {10}^{9}). If there are several solutions, output any of them. One can prove that if there is a solution, then there is also a solution in which all a_i are between 1 and 10^9. If there are no solutions, print "NO". Examples Input 3 2 0 0 2 2 0 Output YES 1 2 1 Input 5 0 1 1 3 2 1 3 0 2 0 Output YES 2 3 2 1 2 Submitted Solution: ``` # https://codeforces.com/contest/1287/problem/D def push(g, u, v): if u not in g: g[u] = [] g[u].append(v) def build(): S = [root] i = 0 order = {} while i < len(S): u = S[i] if u in g: for v in g[u]: S.append(v) i+=1 for u in S[::-1]: order[u] = [] flg=False if u not in g: order[u].append(u) flg=True else: cur = 0 for v in g[u]: for x in order[v]: if cur==cnt[u]: flg=True order[u].append(u) cur+=1 order[u].append(x) cur+=1 if flg == False: if cnt[u] > len(order[u]): return False, root, order else: order[u].append(u) return True, root, order n = int(input()) g = {} cnt = {} for i in range(1, n+1): p, c = map(int, input().split()) cnt[i] = c if p==0: root = i else: push(g, p, i) flg, root, order = build() if flg==False: print('NO') else: ans = [-1] * n for val, u in zip(list(range(n)), order[root]): ans[u-1] = val + 1 print('YES') print(' '.join([str(x) for x in ans])) #5 #0 1 #1 3 #2 1 #3 0 #2 0 #3 #2 0 #0 2 #2 0 ```
instruction
0
53,198
13
106,396
No
output
1
53,198
13
106,397
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Evlampiy was gifted a rooted tree. The vertices of the tree are numbered from 1 to n. Each of its vertices also has an integer a_i written on it. For each vertex i, Evlampiy calculated c_i — the number of vertices j in the subtree of vertex i, such that a_j < a_i. <image>Illustration for the second example, the first integer is a_i and the integer in parentheses is c_i After the new year, Evlampiy could not remember what his gift was! He remembers the tree and the values of c_i, but he completely forgot which integers a_i were written on the vertices. Help him to restore initial integers! Input The first line contains an integer n (1 ≤ n ≤ 2000) — the number of vertices in the tree. The next n lines contain descriptions of vertices: the i-th line contains two integers p_i and c_i (0 ≤ p_i ≤ n; 0 ≤ c_i ≤ n-1), where p_i is the parent of vertex i or 0 if vertex i is root, and c_i is the number of vertices j in the subtree of vertex i, such that a_j < a_i. It is guaranteed that the values of p_i describe a rooted tree with n vertices. Output If a solution exists, in the first line print "YES", and in the second line output n integers a_i (1 ≤ a_i ≤ {10}^{9}). If there are several solutions, output any of them. One can prove that if there is a solution, then there is also a solution in which all a_i are between 1 and 10^9. If there are no solutions, print "NO". Examples Input 3 2 0 0 2 2 0 Output YES 1 2 1 Input 5 0 1 1 3 2 1 3 0 2 0 Output YES 2 3 2 1 2 Submitted Solution: ``` from bisect import bisect_left as bl from bisect import bisect_right as br import heapq import math from collections import * from functools import reduce,cmp_to_key import sys input = sys.stdin.readline # M = mod = 998244353 def factors(n):return sorted(list(set(reduce(list.__add__,([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0))))) # def inv_mod(n):return pow(n, mod - 2, mod) def li():return [int(i) for i in input().rstrip('\n').split(' ')] def st():return input().rstrip('\n') def val():return int(input().rstrip('\n')) def li2():return [i for i in input().rstrip('\n').split(' ')] def li3():return [int(i) for i in input().rstrip('\n')] helpl = defaultdict(deque) def dfs(i): curr = [] # print('currnode : ',i) for j in d[i]: curr.extend(dfs(j)) curr = sorted(list(curr)) # print('currlen : ',curr,'c value : ',c[i-1]) if len(curr) < c[i-1]: print('NO') exit() if not len(curr): curr.append(10000) helpl[10000].append(i-1) else: if c[i-1] == 0: curr.append(curr[0] - 1) helpl[curr[-1]].append(i-1) for j in range(c[i-1]): helpl[curr[j] - 1].append(helpl[curr[j]].popleft()) if j == c[i-1] - 1: helpl[curr[j]].append(i-1) curr.append(curr[j]) curr[j] -= 1 # print(helpl) for i in helpl: if len(helpl[i]): helpl[i] = deque(sorted(helpl[i])) return curr n = val() d = defaultdict(list) c = [] a = [0 for i in range(n)] for i in range(n): x,y = li() d[x].append(i + 1) c.append(y) # print(d) root = d[0][0] d.pop(0) for i in d: d[i] = sorted(d[i]) # print(d,c,root) dfs(root) curr = 1 # print(helpl) for i in sorted(helpl): # print(i) for j in helpl[i]: a[j] = curr curr += 1 print('YES') print(*a) ```
instruction
0
53,199
13
106,398
No
output
1
53,199
13
106,399
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Evlampiy was gifted a rooted tree. The vertices of the tree are numbered from 1 to n. Each of its vertices also has an integer a_i written on it. For each vertex i, Evlampiy calculated c_i — the number of vertices j in the subtree of vertex i, such that a_j < a_i. <image>Illustration for the second example, the first integer is a_i and the integer in parentheses is c_i After the new year, Evlampiy could not remember what his gift was! He remembers the tree and the values of c_i, but he completely forgot which integers a_i were written on the vertices. Help him to restore initial integers! Input The first line contains an integer n (1 ≤ n ≤ 2000) — the number of vertices in the tree. The next n lines contain descriptions of vertices: the i-th line contains two integers p_i and c_i (0 ≤ p_i ≤ n; 0 ≤ c_i ≤ n-1), where p_i is the parent of vertex i or 0 if vertex i is root, and c_i is the number of vertices j in the subtree of vertex i, such that a_j < a_i. It is guaranteed that the values of p_i describe a rooted tree with n vertices. Output If a solution exists, in the first line print "YES", and in the second line output n integers a_i (1 ≤ a_i ≤ {10}^{9}). If there are several solutions, output any of them. One can prove that if there is a solution, then there is also a solution in which all a_i are between 1 and 10^9. If there are no solutions, print "NO". Examples Input 3 2 0 0 2 2 0 Output YES 1 2 1 Input 5 0 1 1 3 2 1 3 0 2 0 Output YES 2 3 2 1 2 Submitted Solution: ``` n = int(input()) adj_list = [[] for i in range(n + 1)] c = [None] for i in range(1, n + 1): p_i, c_i = map(int, input().split()) c.append(c_i) adj_list[p_i].append(i) sizes = [None for i in range(n + 1)] values = [None for i in range(n + 1)] def size(v): sizes[v] = 1 for i in adj_list[v]: size(i) sizes[v] += sizes[i] size(adj_list[0][0]) #print(adj_list) def get_ans(v): if len(adj_list[v]) == 0: return [[1, v]] insert_at = c[v] merged_list = [] current_size = 0 for child in adj_list[v]: ans = get_ans(child) if ans == None: return None merged_list += [[x[0] + current_size, x[1]] for x in ans] current_size += sizes[child] #print(merged_list) if insert_at > len(merged_list) or insert_at < 0: return None new_list = merged_list[:insert_at] new_list.append([insert_at + 1, v]) new_list += [[x[0] + 1, x[1]] for x in merged_list[insert_at:]] #print(new_list) return new_list x = get_ans(adj_list[0][0]) if x == None: print("NO") else: print("YES") #print(x) x.sort(key = lambda i: i[1]) x = [str(a[0]) for a in x] print(" ".join(x)) ```
instruction
0
53,200
13
106,400
No
output
1
53,200
13
106,401
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Evlampiy was gifted a rooted tree. The vertices of the tree are numbered from 1 to n. Each of its vertices also has an integer a_i written on it. For each vertex i, Evlampiy calculated c_i — the number of vertices j in the subtree of vertex i, such that a_j < a_i. <image>Illustration for the second example, the first integer is a_i and the integer in parentheses is c_i After the new year, Evlampiy could not remember what his gift was! He remembers the tree and the values of c_i, but he completely forgot which integers a_i were written on the vertices. Help him to restore initial integers! Input The first line contains an integer n (1 ≤ n ≤ 2000) — the number of vertices in the tree. The next n lines contain descriptions of vertices: the i-th line contains two integers p_i and c_i (0 ≤ p_i ≤ n; 0 ≤ c_i ≤ n-1), where p_i is the parent of vertex i or 0 if vertex i is root, and c_i is the number of vertices j in the subtree of vertex i, such that a_j < a_i. It is guaranteed that the values of p_i describe a rooted tree with n vertices. Output If a solution exists, in the first line print "YES", and in the second line output n integers a_i (1 ≤ a_i ≤ {10}^{9}). If there are several solutions, output any of them. One can prove that if there is a solution, then there is also a solution in which all a_i are between 1 and 10^9. If there are no solutions, print "NO". Examples Input 3 2 0 0 2 2 0 Output YES 1 2 1 Input 5 0 1 1 3 2 1 3 0 2 0 Output YES 2 3 2 1 2 Submitted Solution: ``` from bisect import bisect_left as bl from bisect import bisect_right as br import heapq import math from collections import * from functools import reduce,cmp_to_key import sys input = sys.stdin.readline # M = mod = 998244353 def factors(n):return sorted(list(set(reduce(list.__add__,([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0))))) # def inv_mod(n):return pow(n, mod - 2, mod) def li():return [int(i) for i in input().rstrip('\n').split(' ')] def st():return input().rstrip('\n') def val():return int(input().rstrip('\n')) def li2():return [i for i in input().rstrip('\n').split(' ')] def li3():return [int(i) for i in input().rstrip('\n')] va = 10**7 helpl = defaultdict(deque) def dfs(i): global va curr = [] # print('currnode : ',i) for j in d[i]: curr.extend(dfs(j)) # curr = sorted(list(curr)) # print('currlen : ',curr,'c value : ',c[i-1]) if len(curr) < c[i-1]: print('NO') exit() if not len(curr): curr.append(va) helpl[va].append(i-1) va -= 2000 else: # if c[i-1] == 0: # # curr.append(curr[0] - 1) # helpl[curr[0]].append(i-1) # print(curr) for j in range(c[i-1]): helpl[curr[j] - 1].append(helpl[curr[j]].popleft()) curr[j] -= 1 for j in range(len(curr)-1,c[i-1]-1,-1): helpl[curr[j] + 1].append(helpl[curr[j]].popleft()) helpl[curr[j]] = deque() curr[j] += 1 # print(curr,c[i-1]) if c[i-1] == len(curr):curr.append(curr[-1] + 1) else:curr = curr[:c[i-1]] + [curr[c[i-1]]-1] + curr[c[i-1]:] helpl[curr[c[i-1]]].append(i-1) # print(helpl) # for i in helpl: # if len(helpl[i]): # helpl[i] = deque(sorted(helpl[i])) return curr n = val() d = defaultdict(list) c = [] a = [0 for i in range(n)] for i in range(n): x,y = li() d[x].append(i + 1) c.append(y) # print(d) root = d[0][0] d.pop(0) for i in d: d[i] = sorted(d[i]) # print(d,c,root) dfs(root) curr = 1 # print(helpl) for i in sorted(helpl): # print(i) for j in helpl[i]: a[j] = curr if len(helpl[i]):curr += 1 print('YES') print(*a) ```
instruction
0
53,201
13
106,402
No
output
1
53,201
13
106,403
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Note that the only difference between the easy and hard version is the constraint on the number of queries. You can make hacks only if all versions of the problem are solved. This is an interactive problem. You are given a tree consisting of n nodes numbered with integers from 1 to n. Ayush and Ashish chose two secret distinct nodes in the tree. You need to find out both the nodes. You can make the following query: * Provide a list of nodes and you will receive a node from that list whose sum of distances to both the hidden nodes is minimal (if there are multiple such nodes in the list, you will receive any one of them). You will also get the sum of distances of that node to the hidden nodes. Recall that a tree is a connected graph without cycles. The distance between two nodes is defined as the number of edges in the simple path between them. More formally, let's define two hidden nodes as s and f. In one query you can provide the set of nodes \\{a_1, a_2, …, a_c\} of the tree. As a result, you will get two numbers a_i and dist(a_i, s) + dist(a_i, f). The node a_i is any node from the provided set, for which the number dist(a_i, s) + dist(a_i, f) is minimal. You can ask no more than 11 queries. Input The first line contains a single integer t (1 ≤ t ≤ 10) — the number of test cases. Please note, how the interaction process is organized. The first line of each test case consists of a single integer n (2 ≤ n ≤ 1000) — the number of nodes in the tree. The next n - 1 lines consist of two integers u, v (1 ≤ u, v ≤ n, u ≠ v) — the edges of the tree. Interaction To ask a query print a single line: * In the beginning print "? c " (without quotes) where c (1 ≤ c ≤ n) denotes the number of nodes being queried, followed by c distinct integers in the range [1, n] — the indices of nodes from the list. For each query, you will receive two integers x, d — the node (among the queried nodes) with the minimum sum of distances to the hidden nodes and the sum of distances from that node to the hidden nodes. If the subset of nodes queried is invalid or you exceeded the number of queries then you will get x = d = -1. In this case, you should terminate the program immediately. When you have guessed the hidden nodes, print a single line "! " (without quotes), followed by two integers in the range [1, n] — the hidden nodes. You can output the hidden nodes in any order. After this, you should read a string. If you guess the nodes correctly, you will receive the string "Correct". In this case, you should continue solving the remaining test cases or terminate the program, if all test cases were solved. Otherwise, you will receive the string "Incorrect". In this case, you should terminate the program immediately. Guessing the hidden nodes does not count towards the number of queries asked. The interactor is not adaptive. The hidden nodes do not change with queries. Do not forget to read the string "Correct" / "Incorrect" after guessing the hidden nodes. You need to solve each test case before receiving the input for the next test case. The limit of 11 queries applies to each test case and not to the entire input. After printing a query do not forget to output the end of the line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use: * fflush(stdout) or cout.flush() in C++; * System.out.flush() in Java; * flush(output) in Pascal; * stdout.flush() in Python; * see the documentation for other languages. Hacks To hack the solution, use the following test format: The first line should contain a single integer t (1 ≤ t ≤ 10) — the number of test cases. The description of the test cases follows. The first line of each test case should contain a single integer n (2 ≤ n ≤ 1000) — the number of nodes in the tree. The second line should contain two distinct integers in the range [1, n] — the hidden nodes. The next n - 1 lines should contain two integers u, v (1 ≤ u, v ≤ n, u ≠ v) — the edges of the tree. Example Input 1 3 1 2 1 3 1 1 2 3 3 1 3 1 Correct Output ? 1 1 ? 1 2 ? 1 3 ? 2 2 3 ! 1 3 Note The tree from the first test is shown below, and the hidden nodes are 1 and 3. <image> Submitted Solution: ``` from sys import exit from collections import deque from copy import deepcopy qcount = 0 def readTree(n): adj = [set() for _ in range(n)] for _ in range(n-1): u,v = map(int, input().split()) adj[u-1].add(v-1) adj[v-1].add(u-1) return adj def nodes_at_depth(n, root, adj, d): q = deque() q.append(root) depth = [-1] * n depth[root] = 0 res = [] parent = [-1] * n while q: v = q.popleft() if depth[v] == d: res.append(v) continue for a in adj[v]: if depth[a] == -1: parent[a] = v depth[a] = depth[v] + 1 q.append(a) return res, parent def query(vv, depth): global qcount if qcount > 11: print('!', len(vv), depth) qcount += 1 print('?', len(vv), ' '.join(map(lambda v: str(v+1), vv)), flush=True) v, d = map(int, input().split()) if v == -1: exit() return v-1, d def main(): def solve(): global qcount qcount = 0 n = int(input()) adj = readTree(n) v, w = solvebody(adj, n, query) print('!', v+1, w+1, flush=True) if input() != "Correct": exit() t = int(input()) for _ in range(t): solve() def solvebody(adj, n, query): # Find a node on the path v, d = query(range(n), n) depth = min(d, 500) adjm = deepcopy(adj) while depth > 1: depth = (depth +1) // 2 vv, parent = nodes_at_depth(n, v, adjm, depth) if not vv: continue x, d1 = query(vv, depth) if d1 == d: v = x adjm[v].remove(parent[v]) vv, _ = nodes_at_depth(n, v, adjm, 1) if vv: x, d1 = query(vv, 0) if d1 == d: v = x vv, _ = nodes_at_depth(n, v, adj, d) w, _ = query(vv, -1) return v, w if __name__ == "__main__": main() ```
instruction
0
53,251
13
106,502
No
output
1
53,251
13
106,503
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Note that the only difference between the easy and hard version is the constraint on the number of queries. You can make hacks only if all versions of the problem are solved. This is an interactive problem. You are given a tree consisting of n nodes numbered with integers from 1 to n. Ayush and Ashish chose two secret distinct nodes in the tree. You need to find out both the nodes. You can make the following query: * Provide a list of nodes and you will receive a node from that list whose sum of distances to both the hidden nodes is minimal (if there are multiple such nodes in the list, you will receive any one of them). You will also get the sum of distances of that node to the hidden nodes. Recall that a tree is a connected graph without cycles. The distance between two nodes is defined as the number of edges in the simple path between them. More formally, let's define two hidden nodes as s and f. In one query you can provide the set of nodes \\{a_1, a_2, …, a_c\} of the tree. As a result, you will get two numbers a_i and dist(a_i, s) + dist(a_i, f). The node a_i is any node from the provided set, for which the number dist(a_i, s) + dist(a_i, f) is minimal. You can ask no more than 11 queries. Input The first line contains a single integer t (1 ≤ t ≤ 10) — the number of test cases. Please note, how the interaction process is organized. The first line of each test case consists of a single integer n (2 ≤ n ≤ 1000) — the number of nodes in the tree. The next n - 1 lines consist of two integers u, v (1 ≤ u, v ≤ n, u ≠ v) — the edges of the tree. Interaction To ask a query print a single line: * In the beginning print "? c " (without quotes) where c (1 ≤ c ≤ n) denotes the number of nodes being queried, followed by c distinct integers in the range [1, n] — the indices of nodes from the list. For each query, you will receive two integers x, d — the node (among the queried nodes) with the minimum sum of distances to the hidden nodes and the sum of distances from that node to the hidden nodes. If the subset of nodes queried is invalid or you exceeded the number of queries then you will get x = d = -1. In this case, you should terminate the program immediately. When you have guessed the hidden nodes, print a single line "! " (without quotes), followed by two integers in the range [1, n] — the hidden nodes. You can output the hidden nodes in any order. After this, you should read a string. If you guess the nodes correctly, you will receive the string "Correct". In this case, you should continue solving the remaining test cases or terminate the program, if all test cases were solved. Otherwise, you will receive the string "Incorrect". In this case, you should terminate the program immediately. Guessing the hidden nodes does not count towards the number of queries asked. The interactor is not adaptive. The hidden nodes do not change with queries. Do not forget to read the string "Correct" / "Incorrect" after guessing the hidden nodes. You need to solve each test case before receiving the input for the next test case. The limit of 11 queries applies to each test case and not to the entire input. After printing a query do not forget to output the end of the line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use: * fflush(stdout) or cout.flush() in C++; * System.out.flush() in Java; * flush(output) in Pascal; * stdout.flush() in Python; * see the documentation for other languages. Hacks To hack the solution, use the following test format: The first line should contain a single integer t (1 ≤ t ≤ 10) — the number of test cases. The description of the test cases follows. The first line of each test case should contain a single integer n (2 ≤ n ≤ 1000) — the number of nodes in the tree. The second line should contain two distinct integers in the range [1, n] — the hidden nodes. The next n - 1 lines should contain two integers u, v (1 ≤ u, v ≤ n, u ≠ v) — the edges of the tree. Example Input 1 3 1 2 1 3 1 1 2 3 3 1 3 1 Correct Output ? 1 1 ? 1 2 ? 1 3 ? 2 2 3 ! 1 3 Note The tree from the first test is shown below, and the hidden nodes are 1 and 3. <image> Submitted Solution: ``` from sys import stdin, stdout # 1 # 2 3 # 4 5 6 7 8 # 1. query all nodes to get min distance between hidden nodes. # 2. root No.1 node, binary search for one hidden node. # 3. get another hidden node at querying all nodes satisfy min distance. if __name__ == '__main__': def get_all_nodes(n): res = [] for i in range(n): res.append(i+1) return res def get_nodes(dic, r, d): visited = set() visited.add(r) queue = [r] while len(queue) > 0 and d > 0: n = len(queue) for i in range(n): cur = queue.pop(0) for nxt in dic[cur]: if nxt in visited: continue visited.add(nxt) queue.append(nxt) d -= 1 return queue t = int(stdin.readline()) for i in range(t): n = int(stdin.readline()) dic = {} for j in range(n-1): u, v = map(int, stdin.readline().split()) if u not in dic: dic[u] = [] if v not in dic: dic[v] = [] dic[u].append(v) dic[v].append(u) # 1 cmd = get_all_nodes(n) stdout.write("? " + str(len(cmd)) + " " + " ".join(map(str, cmd)) + '\n') stdout.flush() r, d = map(int, stdin.readline().split()) # 2 node1 = 0 l = 0 h = d while l < h: m = (l + h + 1) // 2 cmd = get_nodes(dic, r, m) if len(cmd) == 0: h = m - 1 continue stdout.write("? " + str(len(cmd)) + " " + " ".join(map(str, cmd)) + '\n') stdout.flush() s_n, s_d = map(int, stdin.readline().split()) if d == s_d: node1 = s_n l = m else: h = m - 1 #cmd = get_nodes(dic, r, l) #stdout.write("? " + str(len(cmd)) + " " + " ".join(map(str, cmd)) + '\n') #stdout.flush() #node1, s_d = map(int, stdin.readline().split()) # 3 node2 = 0 cmd = get_nodes(dic, node1, d) stdout.write("? " + str(len(cmd)) + " " + " ".join(map(str, cmd)) + '\n') stdout.flush() node2, s_d = map(int, stdin.readline().split()) stdout.write("! " + str(node1) + " " + str(node2) + '\n') stdout.flush() res = stdin.readline() ```
instruction
0
53,252
13
106,504
No
output
1
53,252
13
106,505
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Note that the only difference between the easy and hard version is the constraint on the number of queries. You can make hacks only if all versions of the problem are solved. This is an interactive problem. You are given a tree consisting of n nodes numbered with integers from 1 to n. Ayush and Ashish chose two secret distinct nodes in the tree. You need to find out both the nodes. You can make the following query: * Provide a list of nodes and you will receive a node from that list whose sum of distances to both the hidden nodes is minimal (if there are multiple such nodes in the list, you will receive any one of them). You will also get the sum of distances of that node to the hidden nodes. Recall that a tree is a connected graph without cycles. The distance between two nodes is defined as the number of edges in the simple path between them. More formally, let's define two hidden nodes as s and f. In one query you can provide the set of nodes \\{a_1, a_2, …, a_c\} of the tree. As a result, you will get two numbers a_i and dist(a_i, s) + dist(a_i, f). The node a_i is any node from the provided set, for which the number dist(a_i, s) + dist(a_i, f) is minimal. You can ask no more than 11 queries. Input The first line contains a single integer t (1 ≤ t ≤ 10) — the number of test cases. Please note, how the interaction process is organized. The first line of each test case consists of a single integer n (2 ≤ n ≤ 1000) — the number of nodes in the tree. The next n - 1 lines consist of two integers u, v (1 ≤ u, v ≤ n, u ≠ v) — the edges of the tree. Interaction To ask a query print a single line: * In the beginning print "? c " (without quotes) where c (1 ≤ c ≤ n) denotes the number of nodes being queried, followed by c distinct integers in the range [1, n] — the indices of nodes from the list. For each query, you will receive two integers x, d — the node (among the queried nodes) with the minimum sum of distances to the hidden nodes and the sum of distances from that node to the hidden nodes. If the subset of nodes queried is invalid or you exceeded the number of queries then you will get x = d = -1. In this case, you should terminate the program immediately. When you have guessed the hidden nodes, print a single line "! " (without quotes), followed by two integers in the range [1, n] — the hidden nodes. You can output the hidden nodes in any order. After this, you should read a string. If you guess the nodes correctly, you will receive the string "Correct". In this case, you should continue solving the remaining test cases or terminate the program, if all test cases were solved. Otherwise, you will receive the string "Incorrect". In this case, you should terminate the program immediately. Guessing the hidden nodes does not count towards the number of queries asked. The interactor is not adaptive. The hidden nodes do not change with queries. Do not forget to read the string "Correct" / "Incorrect" after guessing the hidden nodes. You need to solve each test case before receiving the input for the next test case. The limit of 11 queries applies to each test case and not to the entire input. After printing a query do not forget to output the end of the line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use: * fflush(stdout) or cout.flush() in C++; * System.out.flush() in Java; * flush(output) in Pascal; * stdout.flush() in Python; * see the documentation for other languages. Hacks To hack the solution, use the following test format: The first line should contain a single integer t (1 ≤ t ≤ 10) — the number of test cases. The description of the test cases follows. The first line of each test case should contain a single integer n (2 ≤ n ≤ 1000) — the number of nodes in the tree. The second line should contain two distinct integers in the range [1, n] — the hidden nodes. The next n - 1 lines should contain two integers u, v (1 ≤ u, v ≤ n, u ≠ v) — the edges of the tree. Example Input 1 3 1 2 1 3 1 1 2 3 3 1 3 1 Correct Output ? 1 1 ? 1 2 ? 1 3 ? 2 2 3 ! 1 3 Note The tree from the first test is shown below, and the hidden nodes are 1 and 3. <image> Submitted Solution: ``` from sys import exit from collections import deque from copy import deepcopy def readTree(n): adj = [set() for _ in range(n)] for _ in range(n-1): u,v = map(int, input().split()) adj[u-1].add(v-1) adj[v-1].add(u-1) return adj def nodes_at_depth(n, root, adj, d): q = deque() q.append(root) depth = [-1] * n depth[root] = 0 res = [] parent = [-1] * n while q: v = q.popleft() if depth[v] == d: res.append(v) continue for a in adj[v]: if depth[a] == -1: parent[a] = v depth[a] = depth[v] + 1 q.append(a) return res, parent def query(vv): print('?', len(vv), ' '.join(map(lambda v: str(v+1), vv)), flush=True) v, d = map(int, input().split()) if v == -1: exit() return v-1, d def main(): def solve(): n = int(input()) adj = readTree(n) v, w = solvebody(adj, n, query) print('!', v+1, w+1, flush=True) if input() != "Correct": exit() t = int(input()) for _ in range(t): solve() def solvebody(adj, n, query): # Find a node on the path v, d = query(range(n)) depth = min(d, 500) adjm = deepcopy(adj) while depth > 1: depth = (depth +1) // 2 vv, parent = nodes_at_depth(n, v, adjm, depth) if not vv: continue x, d1 = query(vv) if d1 == d: v = x adjm[v].remove(parent[v]) vv, _ = nodes_at_depth(n, v, adjm, 1) if vv: x, d1 = query(vv) if d1 == d: v = x vv, _ = nodes_at_depth(n, v, adj, d) w, _ = query(vv) return v, w if __name__ == "__main__": main() ```
instruction
0
53,253
13
106,506
No
output
1
53,253
13
106,507
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Note that the only difference between the easy and hard version is the constraint on the number of queries. You can make hacks only if all versions of the problem are solved. This is an interactive problem. You are given a tree consisting of n nodes numbered with integers from 1 to n. Ayush and Ashish chose two secret distinct nodes in the tree. You need to find out both the nodes. You can make the following query: * Provide a list of nodes and you will receive a node from that list whose sum of distances to both the hidden nodes is minimal (if there are multiple such nodes in the list, you will receive any one of them). You will also get the sum of distances of that node to the hidden nodes. Recall that a tree is a connected graph without cycles. The distance between two nodes is defined as the number of edges in the simple path between them. More formally, let's define two hidden nodes as s and f. In one query you can provide the set of nodes \\{a_1, a_2, …, a_c\} of the tree. As a result, you will get two numbers a_i and dist(a_i, s) + dist(a_i, f). The node a_i is any node from the provided set, for which the number dist(a_i, s) + dist(a_i, f) is minimal. You can ask no more than 11 queries. Input The first line contains a single integer t (1 ≤ t ≤ 10) — the number of test cases. Please note, how the interaction process is organized. The first line of each test case consists of a single integer n (2 ≤ n ≤ 1000) — the number of nodes in the tree. The next n - 1 lines consist of two integers u, v (1 ≤ u, v ≤ n, u ≠ v) — the edges of the tree. Interaction To ask a query print a single line: * In the beginning print "? c " (without quotes) where c (1 ≤ c ≤ n) denotes the number of nodes being queried, followed by c distinct integers in the range [1, n] — the indices of nodes from the list. For each query, you will receive two integers x, d — the node (among the queried nodes) with the minimum sum of distances to the hidden nodes and the sum of distances from that node to the hidden nodes. If the subset of nodes queried is invalid or you exceeded the number of queries then you will get x = d = -1. In this case, you should terminate the program immediately. When you have guessed the hidden nodes, print a single line "! " (without quotes), followed by two integers in the range [1, n] — the hidden nodes. You can output the hidden nodes in any order. After this, you should read a string. If you guess the nodes correctly, you will receive the string "Correct". In this case, you should continue solving the remaining test cases or terminate the program, if all test cases were solved. Otherwise, you will receive the string "Incorrect". In this case, you should terminate the program immediately. Guessing the hidden nodes does not count towards the number of queries asked. The interactor is not adaptive. The hidden nodes do not change with queries. Do not forget to read the string "Correct" / "Incorrect" after guessing the hidden nodes. You need to solve each test case before receiving the input for the next test case. The limit of 11 queries applies to each test case and not to the entire input. After printing a query do not forget to output the end of the line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use: * fflush(stdout) or cout.flush() in C++; * System.out.flush() in Java; * flush(output) in Pascal; * stdout.flush() in Python; * see the documentation for other languages. Hacks To hack the solution, use the following test format: The first line should contain a single integer t (1 ≤ t ≤ 10) — the number of test cases. The description of the test cases follows. The first line of each test case should contain a single integer n (2 ≤ n ≤ 1000) — the number of nodes in the tree. The second line should contain two distinct integers in the range [1, n] — the hidden nodes. The next n - 1 lines should contain two integers u, v (1 ≤ u, v ≤ n, u ≠ v) — the edges of the tree. Example Input 1 3 1 2 1 3 1 1 2 3 3 1 3 1 Correct Output ? 1 1 ? 1 2 ? 1 3 ? 2 2 3 ! 1 3 Note The tree from the first test is shown below, and the hidden nodes are 1 and 3. <image> Submitted Solution: ``` from sys import stdin, stdout # 1 # 2 3 # 4 5 6 7 8 # 1. query all nodes to get min distance between hidden nodes. # 2. root No.1 node, binary search for one hidden node. # 3. get another hidden node at querying all nodes satisfy min distance. if __name__ == '__main__': def get_all_nodes(n): res = [] for i in range(n): res.append(i+1) return res def get_nodes(dic, r, d): visited = set() visited.add(r) queue = [r] while len(queue) > 0 and d > 0: n = len(queue) for i in range(n): cur = queue.pop(0) for nxt in dic[cur]: if nxt in visited: continue queue.append(nxt) d -= 1 return queue t = int(stdin.readline()) for i in range(t): n = int(stdin.readline()) dic = {} for j in range(n-1): u, v = map(int, stdin.readline().split()) if u not in dic: dic[u] = [] if v not in dic: dic[v] = [] dic[u].append(v) dic[v].append(u) # 1 cmd = get_all_nodes(n) print("? " + " ".join(map(str, cmd))) stdout.flush() r, d = map(int, stdin.readline().split()) # 2 node1 = 0 l = 0 h = d while l < h: m = (l + h) // 2 cmd = get_nodes(dic, r, m) print("? " + " ".join(map(str, cmd))) stdout.flush() node1, s_d = map(int, stdin.readline().split()) if d == s_d: h = m else: l = m + 1 # 3 node2 = 0 cmd = get_nodes(dic, node1, d) print("? " + " ".join(map(str, cmd))) stdout.flush() node2, s_d = map(int, stdin.readline().split()) print("! " + str(node1) + " " + str(node2)) stdout.flush() res = stdin.readline() ```
instruction
0
53,254
13
106,508
No
output
1
53,254
13
106,509
Provide a correct Python 3 solution for this coding contest problem. There is a tree with N vertices numbered 1 to N. The i-th edge in this tree connects Vertex a_i and Vertex b_i, and the color and length of that edge are c_i and d_i, respectively. Here the color of each edge is represented by an integer between 1 and N-1 (inclusive). The same integer corresponds to the same color, and different integers correspond to different colors. Answer the following Q queries: * Query j (1 \leq j \leq Q): assuming that the length of every edge whose color is x_j is changed to y_j, find the distance between Vertex u_j and Vertex v_j. (The changes of the lengths of edges do not affect the subsequent queries.) Constraints * 2 \leq N \leq 10^5 * 1 \leq Q \leq 10^5 * 1 \leq a_i, b_i \leq N * 1 \leq c_i \leq N-1 * 1 \leq d_i \leq 10^4 * 1 \leq x_j \leq N-1 * 1 \leq y_j \leq 10^4 * 1 \leq u_j < v_j \leq N * 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 c_1 d_1 : a_{N-1} b_{N-1} c_{N-1} d_{N-1} x_1 y_1 u_1 v_1 : x_Q y_Q u_Q v_Q Output Print Q lines. The j-th line (1 \leq j \leq Q) should contain the answer to Query j. Example Input 5 3 1 2 1 10 1 3 2 20 2 4 4 30 5 2 1 40 1 100 1 4 1 100 1 5 3 1000 3 4 Output 130 200 60
instruction
0
53,703
13
107,406
"Correct Solution: ``` import sys sys.setrecursionlimit(10**6+1) #再帰関数の上限,10**5以上の場合python def input(): x=sys.stdin.readline() return x[:-1] if x[-1]=="\n" else x def printe(*x):print("## ",*x,file=sys.stderr) def printl(li): _=print(*li, sep="\n") if li else None #N, Q = map(int, input().split()) N, Q = map(int, input().split()) #A = tuple(map(int, input().split())) #1行ベクトル #L = tuple(int(input()) for i in range(N)) #改行ベクトル #S = tuple(tuple(map(int, input().split())) for i in range(N)) #改行行列 edge = [[] for i in range(N)] for i in range(N-1):#木の場合M=N-1 a,b,c,w = map(int,input().split()) edge[a-1].append((b-1,c-1,w)) edge[b-1].append((a-1,c-1,w)) #有向のばあいコメントアウト #ダブリングによるLCA, 前処理NlogN, 呼び出しlogN, 安定 def dfs(start): q=[(start,-1,0,0)] pars=[-1]*N depth=[-1]*N dist=[-1]*N while len(q): e,p,d,dis=q.pop()#ここをpopleftにすると幅優先探索BFSになる if depth[e]!=-1:continue pars[e]=p depth[e]=d dist[e]=dis for ne,c,w in edge[e]: q.append((ne,e,d+1,dis+w)) return pars,depth,dist pars,d,dist=dfs(0) ln=N.bit_length() dp=[[-1]*N for _ in range(ln+1)] dp[0]=pars for i in range(1,ln+1): for j in range(N): dp[i][j]=dp[i-1][dp[i-1][j]] # LCAの計算 def lca(u, v): du = d[u]; dv = d[v] if du > dv: du, dv = dv, du u,v=v,u dif=dv-du for i in range(ln+1): if (dif>>i)&1: v=dp[i][v] if u==v:return u for i in range(ln,-1,-1): pu=dp[i][u];pv=dp[i][v] if pu!=pv: u,v=pu,pv return pars[u] q=Q #qs = tuple(tuple(map(int, input().split())) for i in range(Q)) #改行行列 # ans=[0]*Q # qn=[[] for _ in range(N)] # for i,(x,y,u,v) in enumerate(qs): # ans[i]=dist[u-1]+dist[v-1]-dist[lca(u-1,v-1)] # qn[u-1].append((i,x-1,y)) # qn[v-1].append((i,x-1,y)) # cnt=[0]*Q # #printe(qn) # qc=[[0,0] for _ in range(Q)] # cc=[[0,0] for _ in range(N-1)] # dfq=[(0,None,0,-1)] # def dfs2(e,c,d,p): # if c!=None: # cc[c][0]+=1 # cc[c][1]+=d # for qi,x,y in qn[e]: # if cnt[qi]==0: # qc[qi][0]-=cc[x][0] # qc[qi][1]-=cc[x][1] # elif cnt[qi]==1: # qc[qi][0]+=cc[x][0] # qc[qi][1]+=cc[x][1] # ans[qi]+=y*qc[qi][0]-qc[qi][1] # cnt[qi]+=1 # for ne,nc,nd in edge[e]: # if ne==par[e]:continue # dfs2(ne,nc,nd,e) # if c!=None: # cc[c][0]+=1 # cc[c][1]+=d # dfs2(0) # printl(ans) n=N A = [0]*q C = [[] for _ in range(n)] num = [0]*n cum = [0]*n for i in range(q): x, y, u, v = map(int, input().split()) u -= 1 v -= 1 a = lca(u, v) C[u].append((i, x, y, 1)) C[v].append((i, x, y, 1)) C[a].append((i, x, y, -2)) dist = 0 stack = [0] def dfs2(v): global dist for i, x, y, b in C[v]: A[i] += (dist + num[x]*y - cum[x]) * b for nv, c, d in edge[v]: c+=1 if nv ==pars[v]:continue dist += d num[c] += 1 cum[c] += d dfs2(nv) dist -= d num[c] -= 1 cum[c] -= d dfs2(0) print(*A, sep="\n") ```
output
1
53,703
13
107,407
Provide a correct Python 3 solution for this coding contest problem. There is a tree with N vertices numbered 1 to N. The i-th edge in this tree connects Vertex a_i and Vertex b_i, and the color and length of that edge are c_i and d_i, respectively. Here the color of each edge is represented by an integer between 1 and N-1 (inclusive). The same integer corresponds to the same color, and different integers correspond to different colors. Answer the following Q queries: * Query j (1 \leq j \leq Q): assuming that the length of every edge whose color is x_j is changed to y_j, find the distance between Vertex u_j and Vertex v_j. (The changes of the lengths of edges do not affect the subsequent queries.) Constraints * 2 \leq N \leq 10^5 * 1 \leq Q \leq 10^5 * 1 \leq a_i, b_i \leq N * 1 \leq c_i \leq N-1 * 1 \leq d_i \leq 10^4 * 1 \leq x_j \leq N-1 * 1 \leq y_j \leq 10^4 * 1 \leq u_j < v_j \leq N * 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 c_1 d_1 : a_{N-1} b_{N-1} c_{N-1} d_{N-1} x_1 y_1 u_1 v_1 : x_Q y_Q u_Q v_Q Output Print Q lines. The j-th line (1 \leq j \leq Q) should contain the answer to Query j. Example Input 5 3 1 2 1 10 1 3 2 20 2 4 4 30 5 2 1 40 1 100 1 4 1 100 1 5 3 1000 3 4 Output 130 200 60
instruction
0
53,704
13
107,408
"Correct Solution: ``` import sys read = sys.stdin.buffer.read readline = sys.stdin.buffer.readline readlines = sys.stdin.buffer.readlines n,q = map(int,readline().split()) data = list(map(int,read().split())) abcd = data[:4*(n-1)] xyuv = data[4*(n-1):] root = 1 dbl_max = 20 dbl = [[0] * dbl_max for _ in range(n+1)] depth = [0] * (n+1) links = [[] for _ in range(n+1)] it = iter(abcd) for a,b,c,d in zip(it,it,it,it): links[a].append((b,c,d)) links[b].append((a,c,d)) stack = [root] while(stack): i = stack.pop() for j,c,d in links[i]: if(j==dbl[i][0]): continue dbl[j][0] = i depth[j] = depth[i]+1 stack.append(j) for i in range(1,dbl_max): for j in range(1,n+1): dbl[j][i] = dbl[dbl[j][i-1]][i-1] def get_lca(x,y): if(depth[x] > depth[y]): x,y = y,x dif = depth[y]-depth[x] for i in range(dbl_max): if(dif==0): break if(dif>>i)&1: y = dbl[y][i] dif -= (1<<i) for i in range(dbl_max-1,-1,-1): if(dbl[x][i] != dbl[y][i]): x = dbl[x][i] y = dbl[y][i] if(x!=y): return dbl[x][0] else: return x ans = [0] * q query = [[] for _ in range(n+1)] for i in range(q): x,y,u,v = xyuv[i*4:i*4+4] lca = get_lca(u,v) query[u].append((i,x,y,1)) query[v].append((i,x,y,1)) query[lca].append((i,x,y,-2)) tot = 0 c_cost = [[0,0] for _ in range(n)] stack = [] for j,c,d in links[root]: stack.append((root,j,c,d,1)) while(stack): a,b,c,d,num = stack.pop() tot += d*num c_cost[c][0] += d*num c_cost[c][1] += num if(num==1): for qi,x,y,num_q in query[b]: ans[qi] += num_q * (tot - c_cost[x][0] + c_cost[x][1]*y) next = [] for j,c,d in links[b]: if(j==dbl[b][0]): stack.append((b,j,c,d,-1)) else: next.append((b,j,c,d,1)) stack += next # print(c_cost) print('\n'.join(map(str,ans))) ```
output
1
53,704
13
107,409
Provide a correct Python 3 solution for this coding contest problem. There is a tree with N vertices numbered 1 to N. The i-th edge in this tree connects Vertex a_i and Vertex b_i, and the color and length of that edge are c_i and d_i, respectively. Here the color of each edge is represented by an integer between 1 and N-1 (inclusive). The same integer corresponds to the same color, and different integers correspond to different colors. Answer the following Q queries: * Query j (1 \leq j \leq Q): assuming that the length of every edge whose color is x_j is changed to y_j, find the distance between Vertex u_j and Vertex v_j. (The changes of the lengths of edges do not affect the subsequent queries.) Constraints * 2 \leq N \leq 10^5 * 1 \leq Q \leq 10^5 * 1 \leq a_i, b_i \leq N * 1 \leq c_i \leq N-1 * 1 \leq d_i \leq 10^4 * 1 \leq x_j \leq N-1 * 1 \leq y_j \leq 10^4 * 1 \leq u_j < v_j \leq N * 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 c_1 d_1 : a_{N-1} b_{N-1} c_{N-1} d_{N-1} x_1 y_1 u_1 v_1 : x_Q y_Q u_Q v_Q Output Print Q lines. The j-th line (1 \leq j \leq Q) should contain the answer to Query j. Example Input 5 3 1 2 1 10 1 3 2 20 2 4 4 30 5 2 1 40 1 100 1 4 1 100 1 5 3 1000 3 4 Output 130 200 60
instruction
0
53,705
13
107,410
"Correct Solution: ``` import sys input = sys.stdin.readline sys.setrecursionlimit(10**7) N, Q = map(int, input().split()) graph = [[] for _ in range(N+1)] for _ in range(N-1): a, b, c, d = map(int, input().split()) graph[a].append((b, c, d)) graph[b].append((a, c, d)) query = [[int(x) for x in input().split()] for _ in range(Q)] depth = [0] * (N+1) U = 17 ancestor = [[0] * (U+1) for _ in range(N+1)] q = [(1, 0, 0)] while q: qq = [] for x, d, parent in q: depth[x] = d ax = ancestor[x] ax[0] = parent for i in range(d.bit_length()-1): ax[i+1] = ancestor[ax[i]][i] for y, _, _ in graph[x]: if y == parent: continue qq.append((y, d+1, x)) q = qq def LCA(x, y): dx = depth[x] dy = depth[y] if dx > dy: x, y = y, x dx, dy = dy, dx diff = dy - dx while diff: step = diff & (-diff) y = ancestor[y][step.bit_length()-1] diff -= step while x != y: j = 0 while ancestor[x][j] != ancestor[y][j]: j += 1 if j == 0: return ancestor[x][0] x = ancestor[x][j-1] y = ancestor[y][j-1] return x tasks = [[] for _ in range(N+1)] for i, (x, y, u, v) in enumerate(query): tasks[u].append((i, x, y, 1)) tasks[v].append((i, x, y, 1)) tasks[LCA(u, v)].append((i, x, y, -2)) answer = [0] * Q def dfs(x = 1, sums = [0] * (N+1), nums = [0] * (N+1), total = 0, parent = 0): for i, c, d, coef in tasks[x]: answer[i] += coef * (total - sums[c] + nums[c] * d) for y, c, d in graph[x]: if y == parent: continue sums[c] += d nums[c] += 1 total += d dfs(y, sums, nums, total, x) sums[c] -= d nums[c] -= 1 total -= d return dfs() print('\n'.join(map(str, answer))) ```
output
1
53,705
13
107,411
Provide a correct Python 3 solution for this coding contest problem. There is a tree with N vertices numbered 1 to N. The i-th edge in this tree connects Vertex a_i and Vertex b_i, and the color and length of that edge are c_i and d_i, respectively. Here the color of each edge is represented by an integer between 1 and N-1 (inclusive). The same integer corresponds to the same color, and different integers correspond to different colors. Answer the following Q queries: * Query j (1 \leq j \leq Q): assuming that the length of every edge whose color is x_j is changed to y_j, find the distance between Vertex u_j and Vertex v_j. (The changes of the lengths of edges do not affect the subsequent queries.) Constraints * 2 \leq N \leq 10^5 * 1 \leq Q \leq 10^5 * 1 \leq a_i, b_i \leq N * 1 \leq c_i \leq N-1 * 1 \leq d_i \leq 10^4 * 1 \leq x_j \leq N-1 * 1 \leq y_j \leq 10^4 * 1 \leq u_j < v_j \leq N * 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 c_1 d_1 : a_{N-1} b_{N-1} c_{N-1} d_{N-1} x_1 y_1 u_1 v_1 : x_Q y_Q u_Q v_Q Output Print Q lines. The j-th line (1 \leq j \leq Q) should contain the answer to Query j. Example Input 5 3 1 2 1 10 1 3 2 20 2 4 4 30 5 2 1 40 1 100 1 4 1 100 1 5 3 1000 3 4 Output 130 200 60
instruction
0
53,706
13
107,412
"Correct Solution: ``` from collections import defaultdict, deque, Counter from heapq import heappush, heappop, heapify import math import bisect import random from itertools import permutations, accumulate, combinations, product import sys from pprint import pprint from copy import deepcopy import string from bisect import bisect_left, bisect_right from math import factorial, ceil, floor from operator import mul from functools import reduce from pprint import pprint sys.setrecursionlimit(2147483647) INF = 10 ** 13 def LI(): return list(map(int, sys.stdin.buffer.readline().split())) def I(): return int(sys.stdin.buffer.readline()) def LS(): return sys.stdin.buffer.readline().rstrip().decode('utf-8').split() def S(): return sys.stdin.buffer.readline().rstrip().decode('utf-8') def IR(n): return [I() for i in range(n)] def LIR(n): return [LI() for i in range(n)] def SR(n): return [S() for i in range(n)] def LSR(n): return [LS() for i in range(n)] def SRL(n): return [list(S()) for i in range(n)] def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)] mod = 1000000007 class LCA: def __init__(self,v,Edges,root=0): self.v=v self.Edges=Edges self.maxLog=18 self.Parent=[[-1]*v for _ in range(self.maxLog+1)] self.Depth=[0]*v self.__bfs(root) for i in range(self.maxLog): for j in range(v): if self.Parent[i][j]!=-1: self.Parent[i+1][j]=self.Parent[i][self.Parent[i][j]] def __bfs(self,root): Visited=[False]*self.v Visited[root]=True q=deque([root]) while q: fr=q.pop() for to in self.Edges[fr]: if Visited[to]: continue self.Parent[0][to]=fr self.Depth[to]=self.Depth[fr]+1 Visited[to]=True q.append(to) def lca(self,a,b): if self.Depth[a]>self.Depth[b]: a,b=b,a for i in range(self.maxLog): if (self.Depth[b]-self.Depth[a])&(1<<i): b=self.Parent[i][b] if a==b: return b for i in reversed(range(self.maxLog-1)): if self.Parent[i][a]!=self.Parent[i][b]: a=self.Parent[i][a] b=self.Parent[i][b] return self.Parent[0][a] # query先読みで、頂点ごとに、どの色の長さを求めるのか。 n, q = LI() edge_dict = [{} for _ in range(n)] for u, v, c, d in LIR(n - 1): edge_dict[u - 1][v - 1] = (c, d) edge_dict[v - 1][u - 1] = (c, d) lca = LCA(n, edge_dict) query = [[] for _ in range(n)] for q_idx, (x, y, u, v) in enumerate(LIR(q)): query[u - 1] += [(q_idx, x, y, 1)] query[v - 1] += [(q_idx, x, y, 1)] query[lca.lca(u - 1, v - 1)] += [(q_idx, x, y, 0)] def euler_tour(G, root=0): n = len(G) euler = [] depth = [-1] * n depth[root] = 0 dq = [root] dq2 = deque() visited = [0] * n while dq: u = dq.pop() euler += [(depth[u], u)] if visited[u]: continue for v in G[u]: if visited[v]: dq += [v] # [親頂点、子頂点、子頂点、。。。]と入れていく.その後連結 else: depth[v] = depth[u] + 1 dq2 += [v] dq.extend(dq2) dq2 = deque() visited[u] = 1 return euler dist = 0 color_len = [0] * n color_cnt = [0] * n ans = [0] * q euler = euler_tour(edge_dict) for i in range(1, len(euler)): dep = euler[i][0] c, d = edge_dict[euler[i - 1][1]][euler[i][1]] if euler[i - 1][0] < euler[i][0]: dist += d color_len[c] += d color_cnt[c] += 1 for q_idx, x, y, flag in query[euler[i][1]]: if flag: ans[q_idx] += dist - color_len[x] + color_cnt[x] * y else: ans[q_idx] -= (dist - color_len[x] + color_cnt[x] * y) * 2 else: dist -= d color_len[c] -= d color_cnt[c] -= 1 print(*ans, sep='\n') ```
output
1
53,706
13
107,413
Provide a correct Python 3 solution for this coding contest problem. There is a tree with N vertices numbered 1 to N. The i-th edge in this tree connects Vertex a_i and Vertex b_i, and the color and length of that edge are c_i and d_i, respectively. Here the color of each edge is represented by an integer between 1 and N-1 (inclusive). The same integer corresponds to the same color, and different integers correspond to different colors. Answer the following Q queries: * Query j (1 \leq j \leq Q): assuming that the length of every edge whose color is x_j is changed to y_j, find the distance between Vertex u_j and Vertex v_j. (The changes of the lengths of edges do not affect the subsequent queries.) Constraints * 2 \leq N \leq 10^5 * 1 \leq Q \leq 10^5 * 1 \leq a_i, b_i \leq N * 1 \leq c_i \leq N-1 * 1 \leq d_i \leq 10^4 * 1 \leq x_j \leq N-1 * 1 \leq y_j \leq 10^4 * 1 \leq u_j < v_j \leq N * 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 c_1 d_1 : a_{N-1} b_{N-1} c_{N-1} d_{N-1} x_1 y_1 u_1 v_1 : x_Q y_Q u_Q v_Q Output Print Q lines. The j-th line (1 \leq j \leq Q) should contain the answer to Query j. Example Input 5 3 1 2 1 10 1 3 2 20 2 4 4 30 5 2 1 40 1 100 1 4 1 100 1 5 3 1000 3 4 Output 130 200 60
instruction
0
53,707
13
107,414
"Correct Solution: ``` import sys from collections import defaultdict readline = sys.stdin.readline N, Q = map(int, readline().split()) def process(): INF = (N, None) M = 2*N M0 = 2**(M-1).bit_length() data = [INF]*(2*M0) G = [[] for _ in range(N)] dp = {} for v in range(N-1): a, b, c, d = map(int, readline().split()) a, b = a-1, b-1 G[a].append(b) G[b].append(a) dp[(min(a,b), max(a,b))] = c, d S = [0]*(2*N) F = [0]*(2*N) stack = [0] + G[0][::-1] visited = set([0]) depth = [0]*N depthh = [0]*N mmn = [[0] for _ in range(N)] msn = [[0] for _ in range(N)] iin = [[] for _ in range(N)] ccs = [0]*N path = [0] ii = 0 d = 0 dd = 0 while True: if len(stack) == 0: break v = stack.pop() if v in visited: continue ii += 1 if v >=0: visited.add(v) cc, dpd = dp[(min(v,path[-1]), max(v,path[-1]))] F[v] = ii S[ii] = v d += 1 dd += dpd depth[v] = d depthh[v] = dd ccs[v] = cc mmn[cc].append(mmn[cc][-1]+1) msn[cc].append(msn[cc][-1]+dpd) iin[cc].append(v) path.append(v) stack += [-v] + G[v][::-1] else: cc, dpd = dp[(min(path[-1], path[-2]), max(path[-1],path[-2]))] dd -= dpd mmn[cc].append(mmn[cc][-1]-1) iin[cc].append(-path[-1]) msn[cc].append(msn[cc][-1]-dpd) F[-path[-1]] = ii path.pop() S[ii] = path[-1] d -= 1 for i, v in enumerate(S): data[M0-1+i] = (depth[v], i) for i in range(M0-2, -1, -1): data[i] = min(data[2*i+1], data[2*i+2]) for q in range(Q): x, y, u, v = map(int, readline().split()) u, v = u-1, v-1 fu = F[u]; fv = F[v] if fu > fv: fu, fv = fv, fu minx = INF a, b = fu, fv+1 a += M0; b += M0 while a < b: if b & 1: b -= 1 minx = min(minx, data[b-1]) if a & 1: minx = min(minx, data[a-1]) a += 1 a >>= 1; b >>= 1 cc = S[minx[1]] if len(mmn[x])-1 == 0: diff = 0 else: ll, mm, ms, lncc = iin[x], mmn[x], msn[x], len(mmn[x])-2 uvcs = [] for target_i in [F[u], F[v], F[cc]]: ind, lw, hw = (len(mmn[x])-2)//2, 0, len(mmn[x]) - 2 if target_i < F[ll[0]] or target_i >= F[ll[lncc]]: uvcs.append((0,0)) else: while True: if F[ll[ind]] <= target_i: if target_i < F[ll[ind+1]]: uvcs.append((mm[ind+1], ms[ind+1])) break ind, lw = (ind+1 + hw)//2, ind+1 continue ind, hw = (ind-1 + lw)//2, ind-1 diff = (uvcs[0][0] + uvcs[1][0] - 2 * uvcs[2][0]) * y - (uvcs[0][1] + uvcs[1][1] - 2 * uvcs[2][1]) print(depthh[u] + depthh[v] - 2*depthh[cc] + diff) if __name__ == '__main__': process() ```
output
1
53,707
13
107,415
Provide a correct Python 3 solution for this coding contest problem. There is a tree with N vertices numbered 1 to N. The i-th edge in this tree connects Vertex a_i and Vertex b_i, and the color and length of that edge are c_i and d_i, respectively. Here the color of each edge is represented by an integer between 1 and N-1 (inclusive). The same integer corresponds to the same color, and different integers correspond to different colors. Answer the following Q queries: * Query j (1 \leq j \leq Q): assuming that the length of every edge whose color is x_j is changed to y_j, find the distance between Vertex u_j and Vertex v_j. (The changes of the lengths of edges do not affect the subsequent queries.) Constraints * 2 \leq N \leq 10^5 * 1 \leq Q \leq 10^5 * 1 \leq a_i, b_i \leq N * 1 \leq c_i \leq N-1 * 1 \leq d_i \leq 10^4 * 1 \leq x_j \leq N-1 * 1 \leq y_j \leq 10^4 * 1 \leq u_j < v_j \leq N * 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 c_1 d_1 : a_{N-1} b_{N-1} c_{N-1} d_{N-1} x_1 y_1 u_1 v_1 : x_Q y_Q u_Q v_Q Output Print Q lines. The j-th line (1 \leq j \leq Q) should contain the answer to Query j. Example Input 5 3 1 2 1 10 1 3 2 20 2 4 4 30 5 2 1 40 1 100 1 4 1 100 1 5 3 1000 3 4 Output 130 200 60
instruction
0
53,708
13
107,416
"Correct Solution: ``` class Tree(): def __init__(self, n, decrement=1): self.n = n self.edges = [[] for _ in range(n)] self.edges2 = [[] for _ in range(n)] self.root = None self.depth = [-1]*n self.size = [1]*n # 部分木のノードの数 self.color = [[] for _ in range(n)] self.cost = [0]*n self.decrement = decrement def add_edge(self, u, v): u, v = u-self.decrement, v-self.decrement self.edges[u].append(v) self.edges[v].append(u) def add_edges(self, edges): for u, v, c, d in edges: u, v = u-self.decrement, v-self.decrement self.edges[u].append(v) self.edges[v].append(u) self.edges2[u].append((v, c, d)) self.edges2[v].append((u, c, d)) def set_root(self, root): root -= self.decrement self.root = root self.par = [-1]*self.n self.depth[root] = 0 self.order = [root] # 帰りがけに使う next_set = [root] while next_set: p = next_set.pop() for q, c, d in self.edges2[p]: if self.depth[q] != -1: continue self.par[q] = p self.color[c].append(q) self.cost[q] = d self.depth[q] = self.depth[p]+1 self.order.append(q) next_set.append(q) for p in self.order[::-1]: for q in self.edges[p]: if self.par[p] == q: continue self.size[p] += self.size[q] def heavy_light_decomposition(self): """ heavy edge を並べてリストにした物を返す (1-indexed if decrement=True) """ # assert self.root is not None self.vid = [-1]*self.n self.hld = [-1]*self.n self.head = [-1]*self.n self.head[self.root] = self.root self.heavy_node = [-1]*self.n next_set = [self.root] for i in range(self.n): """ for tree graph, dfs ends in N times """ p = next_set.pop() self.vid[p] = i self.hld[i] = p+self.decrement maxs = 0 for q in self.edges[p]: """ encode direction of Heavy edge into heavy_node """ if self.par[p] == q: continue if maxs < self.size[q]: maxs = self.size[q] self.heavy_node[p] = q for q in self.edges[p]: """ determine "head" of heavy edge """ if self.par[p] == q or self.heavy_node[p] == q: continue self.head[q] = q next_set.append(q) if self.heavy_node[p] != -1: self.head[self.heavy_node[p]] = self.head[p] next_set.append(self.heavy_node[p]) return self.hld def lca(self, u, v): # assert self.head is not None u, v = u-self.decrement, v-self.decrement while True: if self.vid[u] > self.vid[v]: u, v = v, u if self.head[u] != self.head[v]: v = self.par[self.head[v]] else: return u + self.decrement def distance(self, u, v): # assert self.head is not None p = self.lca(u, v) u, v, p = u-self.decrement, v-self.decrement, p-self.decrement return self.depth[u] + self.depth[v] - 2*self.depth[p] def find(self, u, v, x): return self.distance(u,x)+self.distance(x,v)==self.distance(u,v) def path_to_list(self, u, v, edge_query=False): """ パス上の頂点の集合を self.hld 上の開区間の集合として表す ここで、self.hld は heavy edge を並べて数列にしたものである """ # assert self.head is not None u, v = u-self.decrement, v-self.decrement while True: if self.vid[u] > self.vid[v]: u, v = v, u if self.head[u] != self.head[v]: yield self.vid[self.head[v]], self.vid[v] + 1 v = self.par[self.head[v]] else: yield self.vid[u] + edge_query, self.vid[v] + 1 return def point(self, u): return self.vid[u-self.decrement] class SegmentTree: def __init__(self, n, op, e): """ :param n: 要素数 :param op: 二項演算 :param e: 単位減 """ self.n = n self.op = op self.e = e self.size = 1 << (self.n - 1).bit_length() # st[self.size + i] = array[i] self.tree = [self.e] * (self.size << 1) def built(self, array): """arrayを初期値とするセグメント木を構築""" for i in range(self.n): self.tree[self.size + i] = array[i] for i in range(self.size - 1, 0, -1): self.tree[i] = self.op(self.tree[i<<1], self.tree[(i<<1)|1]) def update(self, i, x): """i 番目の要素を x に更新 (0-indexed) """ i += self.size self.tree[i] = x while i > 1: i >>= 1 self.tree[i] = self.op(self.tree[i<<1], self.tree[(i<<1)|1]) def get(self, l, r): """ [l, r)の区間取得の結果を返す (0-indexed) """ l += self.size r += self.size res_l = self.e res_r = self.e while l < r: if l & 1: res_l = self.op(res_l, self.tree[l]) l += 1 if r & 1: r -= 1 res_r = self.op(self.tree[r], res_r) l >>= 1 r >>= 1 return self.op(res_l, res_r) def max_right(self, l, f): """ 以下の条件を両方満たす r を(いずれか一つ)返す ・r = l or f(op(a[l], a[l + 1], ..., a[r - 1])) = true ・r = n or f(op(a[l], a[l + 1], ..., a[r])) = false """ if l == self.n: return self.n l += self.size sm = self.e while True: while l % 2 == 0: l >>= 1 if not f(self.op(sm, self.tree[l])): while l < self.size: l = 2 * l if f(self.op(sm, self.tree[l])): sm = self.op(sm, self.tree[l]) l += 1 return l - self.size sm = self.op(sm, self.tree[l]) l += 1 if (l & -l) == l: break return self.n def min_left(self, r, f): """ 以下の条件を両方満たす l を(いずれか一つ)返す ・l = r or f(op(a[l], a[l + 1], ..., a[r - 1])) = true ・l = 0 or f(op(a[l - 1], a[l], ..., a[r - 1])) = false """ if r == 0: return 0 r += self.size sm = self.e while True: r -= 1 while r > 1 and (r % 2): r >>= 1 if not f(self.op(self.tree[r], sm)): while r < self.size: r = 2 * r + 1 if f(self.op(self.tree[r], sm)): sm = self.op(self.tree[r], sm) r -= 1 return r + 1 - self.size sm = self.op(self.tree[r], sm) if (r & -r) == r: break return 0 def __iter__(self): for a in self.tree[self.size:self.size+self.n]: yield a def __str__(self): return str(self.tree[self.size:self.size+self.n]) ######################################################################################################### import sys input = sys.stdin.readline N, Q = map(int, input().split()) tree = Tree(N) edges, query = [], [[] for _ in range(N)] for _ in range(N-1): a, b, c, d = map(int, input().split()) edges.append((a, b, c-1, d)) for i in range(Q): c, y, u, v = map(int, input().split()) query[c-1].append((y, u, v, i)) tree.add_edges(edges) tree.set_root(1) hld = tree.heavy_light_decomposition() e = (0, 0) op = lambda x, y: (x[0]+y[0], x[1]+y[1]) st = SegmentTree(N, op, e) res = [0]*Q for p in range(N): st.update(tree.point(p+1), (tree.cost[p],0)) for c in range(N): for p in tree.color[c]: st.update(tree.point(p+1), (0,1)) for y, u, v, i in query[c]: for l, r in tree.path_to_list(u, v, True): cost, cnt = st.get(l, r) res[i] += cost + cnt*y for p in tree.color[c]: st.update(tree.point(p+1), (tree.cost[p],0)) print(*res, sep="\n") ```
output
1
53,708
13
107,417
Provide a correct Python 3 solution for this coding contest problem. There is a tree with N vertices numbered 1 to N. The i-th edge in this tree connects Vertex a_i and Vertex b_i, and the color and length of that edge are c_i and d_i, respectively. Here the color of each edge is represented by an integer between 1 and N-1 (inclusive). The same integer corresponds to the same color, and different integers correspond to different colors. Answer the following Q queries: * Query j (1 \leq j \leq Q): assuming that the length of every edge whose color is x_j is changed to y_j, find the distance between Vertex u_j and Vertex v_j. (The changes of the lengths of edges do not affect the subsequent queries.) Constraints * 2 \leq N \leq 10^5 * 1 \leq Q \leq 10^5 * 1 \leq a_i, b_i \leq N * 1 \leq c_i \leq N-1 * 1 \leq d_i \leq 10^4 * 1 \leq x_j \leq N-1 * 1 \leq y_j \leq 10^4 * 1 \leq u_j < v_j \leq N * 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 c_1 d_1 : a_{N-1} b_{N-1} c_{N-1} d_{N-1} x_1 y_1 u_1 v_1 : x_Q y_Q u_Q v_Q Output Print Q lines. The j-th line (1 \leq j \leq Q) should contain the answer to Query j. Example Input 5 3 1 2 1 10 1 3 2 20 2 4 4 30 5 2 1 40 1 100 1 4 1 100 1 5 3 1000 3 4 Output 130 200 60
instruction
0
53,709
13
107,418
"Correct Solution: ``` import sys sys.setrecursionlimit(10**5+5) from collections import defaultdict,deque input = sys.stdin.readline class LCA: def __init__(self,n): self.size = n+1 self.bitlen = n.bit_length() self.lca = [[0]*self.size for i in range(self.bitlen)] self.depth = [-1]*self.size self.dis = [-1]*self.size self.depth[1] = 0 self.dis[1] = 0 def make(self,root): q = deque([root]) while q: now = q.popleft() for nex,c,w in e[now]: if self.depth[nex]>= 0: continue self.depth[nex] = self.depth[now]+1 self.dis[nex] = self.dis[now]+w self.lca[0][nex] = now q.append(nex) for i in range(1,self.bitlen): for j in range(self.size): if self.lca[i-1][j] > 0: self.lca[i][j] = self.lca[i-1][self.lca[i-1][j]] def search(self,x,y): dx = self.depth[x] dy = self.depth[y] if dx < dy: x,y = y,x dx,dy = dy,dx dif = dx-dy while dif: s = dif & (-dif) x = self.lca[s.bit_length()-1][x] dif -= s if x == y: return x for i in range(self.bitlen-1,-1,-1): if self.lca[i][x] != self.lca[i][y]: x = self.lca[i][x] y = self.lca[i][y] return self.lca[0][x] n,q = map(int,input().split()) e = [[] for i in range(n+1)] for i in range(n-1): a,b,c,d = map(int,input().split()) e[a].append((b,c,d)) e[b].append((a,c,d)) lca = LCA(n) lca.make(1) Q = [] dcount = defaultdict(lambda : defaultdict(int)) dweight = defaultdict(lambda : defaultdict(int)) for i in range(q): x,y,u,v = map(int,input().split()) a = lca.search(u,v) dcount[u][x] = 0 dcount[v][x] = 0 dcount[a][x] = 0 dweight[u][x] = 0 dweight[v][x] = 0 dweight[a][x] = 0 Q.append((x,y,u,v,a)) dis = [0]*(n+1) def dfs1(now,p,count1,count2): for cou in dcount[now]: dcount[now][cou] = count1[cou] for wei in dweight[now]: dweight[now][wei] = count2[wei] for nex,c,w in e[now]: if nex == p: continue count1[c] += 1 count2[c] += w dis[nex] =dis[now]+w dfs1(nex,now,count1,count2) count1[c] -= 1 count2[c] -= w dfs1(1,0,defaultdict(int),defaultdict(int)) for x,y,u,v,a in Q: cal = dis[u]+dis[v]-2*dis[a] cal += y*(dcount[u][x]+dcount[v][x]-2*dcount[a][x]) - dweight[u][x]-dweight[v][x]+2*dweight[a][x] print(cal) ```
output
1
53,709
13
107,419
Provide a correct Python 3 solution for this coding contest problem. There is a tree with N vertices numbered 1 to N. The i-th edge in this tree connects Vertex a_i and Vertex b_i, and the color and length of that edge are c_i and d_i, respectively. Here the color of each edge is represented by an integer between 1 and N-1 (inclusive). The same integer corresponds to the same color, and different integers correspond to different colors. Answer the following Q queries: * Query j (1 \leq j \leq Q): assuming that the length of every edge whose color is x_j is changed to y_j, find the distance between Vertex u_j and Vertex v_j. (The changes of the lengths of edges do not affect the subsequent queries.) Constraints * 2 \leq N \leq 10^5 * 1 \leq Q \leq 10^5 * 1 \leq a_i, b_i \leq N * 1 \leq c_i \leq N-1 * 1 \leq d_i \leq 10^4 * 1 \leq x_j \leq N-1 * 1 \leq y_j \leq 10^4 * 1 \leq u_j < v_j \leq N * 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 c_1 d_1 : a_{N-1} b_{N-1} c_{N-1} d_{N-1} x_1 y_1 u_1 v_1 : x_Q y_Q u_Q v_Q Output Print Q lines. The j-th line (1 \leq j \leq Q) should contain the answer to Query j. Example Input 5 3 1 2 1 10 1 3 2 20 2 4 4 30 5 2 1 40 1 100 1 4 1 100 1 5 3 1000 3 4 Output 130 200 60
instruction
0
53,710
13
107,420
"Correct Solution: ``` import sys from collections import defaultdict readline = sys.stdin.readline N, Q = map(int, readline().split()) def process(): INF = (N, None) M = 2*N M0 = 2**(M-1).bit_length() data = [INF]*(2*M0) lnc = [0]*N G = [[] for _ in range(N)] dp = {} for v in range(N-1): a, b, c, d = map(int, readline().split()) a, b = a-1, b-1 G[a].append(b) G[b].append(a) dp[(min(a,b), max(a,b))] = c, d S = [0]*(2*N) F = [0]*(2*N) stack = [0] + G[0][::-1] visited = set([0]) depth = [0]*N depthh = [0]*N mmn = [[0] for _ in range(N)] msn = [[0] for _ in range(N)] iin = [[] for _ in range(N)] ccs = [0]*N path = [0] ii = 0 d = 0 dd = 0 while True: if len(stack) == 0: break v = stack.pop() if v in visited: continue ii += 1 if v >=0: visited.add(v) cc, dpd = dp[(min(v,path[-1]), max(v,path[-1]))] F[v] = ii S[ii] = v d += 1 dd += dpd depth[v] = d depthh[v] = dd ccs[v] = cc mmn[cc].append(mmn[cc][-1]+1) msn[cc].append(msn[cc][-1]+dpd) iin[cc].append(v) path.append(v) stack += [-v] + G[v][::-1] else: cc, dpd = dp[(min(path[-1], path[-2]), max(path[-1],path[-2]))] dd -= dpd mmn[cc].append(mmn[cc][-1]-1) iin[cc].append(-path[-1]) msn[cc].append(msn[cc][-1]-dpd) F[-path[-1]] = ii path.pop() S[ii] = path[-1] d -= 1 for i, z in enumerate(mmn): lnc[i] = len(z)-1 for i, v in enumerate(S): data[M0-1+i] = (depth[v], i) for i in range(M0-2, -1, -1): data[i] = min(data[2*i+1], data[2*i+2]) for q in range(Q): x, y, u, v = map(int, readline().split()) u, v = u-1, v-1 fu = F[u]; fv = F[v] if fu > fv: fu, fv = fv, fu minx = INF a, b = fu, fv+1 a += M0; b += M0 while a < b: if b & 1: b -= 1 minx = min(minx, data[b-1]) if a & 1: minx = min(minx, data[a-1]) a += 1 a >>= 1; b >>= 1 cc = S[minx[1]] if lnc[x] == 0: diff = 0 else: ll, mm, ms, lncc = iin[x], mmn[x], msn[x], lnc[x]-1 uvcs = [] for target_i in [F[u], F[v], F[cc]]: ind, lw, hw = (lnc[x]-1)//2, 0, lnc[x]-1 if target_i < F[ll[0]] or target_i >= F[ll[lncc]]: uvcs.append((0,0)) else: while True: if F[ll[ind]] <= target_i: if target_i < F[ll[ind+1]]: uvcs.append((mm[ind+1], ms[ind+1])) break ind, lw = (ind+1 + hw)//2, ind+1 continue ind, hw = (ind-1 + lw)//2, ind-1 diff = (uvcs[0][0] + uvcs[1][0] - 2 * uvcs[2][0]) * y - (uvcs[0][1] + uvcs[1][1] - 2 * uvcs[2][1]) print(depthh[u] + depthh[v] - 2*depthh[cc] + diff) if __name__ == '__main__': process() ```
output
1
53,710
13
107,421
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a tree with N vertices numbered 1 to N. The i-th edge in this tree connects Vertex a_i and Vertex b_i, and the color and length of that edge are c_i and d_i, respectively. Here the color of each edge is represented by an integer between 1 and N-1 (inclusive). The same integer corresponds to the same color, and different integers correspond to different colors. Answer the following Q queries: * Query j (1 \leq j \leq Q): assuming that the length of every edge whose color is x_j is changed to y_j, find the distance between Vertex u_j and Vertex v_j. (The changes of the lengths of edges do not affect the subsequent queries.) Constraints * 2 \leq N \leq 10^5 * 1 \leq Q \leq 10^5 * 1 \leq a_i, b_i \leq N * 1 \leq c_i \leq N-1 * 1 \leq d_i \leq 10^4 * 1 \leq x_j \leq N-1 * 1 \leq y_j \leq 10^4 * 1 \leq u_j < v_j \leq N * 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 c_1 d_1 : a_{N-1} b_{N-1} c_{N-1} d_{N-1} x_1 y_1 u_1 v_1 : x_Q y_Q u_Q v_Q Output Print Q lines. The j-th line (1 \leq j \leq Q) should contain the answer to Query j. Example Input 5 3 1 2 1 10 1 3 2 20 2 4 4 30 5 2 1 40 1 100 1 4 1 100 1 5 3 1000 3 4 Output 130 200 60 Submitted Solution: ``` import sys from itertools import combinations, permutations, product, combinations_with_replacement, accumulate from heapq import heapify, heappop, heappush, heappushpop from bisect import bisect_left, bisect_right from collections import Counter, defaultdict, deque from math import sqrt, log, floor, ceil, factorial, cos, sin, pi#, gcd from fractions import gcd from operator import mul from functools import reduce sys.setrecursionlimit(10**8) input = sys.stdin.readline INF = float('inf') LINF = 2**63-1 NIL = -LINF MOD = 10**9+7 MGN = 4 def AST(exp: bool, msg: str = ""): assert exp, msg def TAST(exp: bool, msg = ""): if exp is False: print("TAssertionError:", msg) while exp is False: pass def EPR(msg): print(msg, file=sys.stderr) def II(): return int(input()) def IF(): return float(input()) def IS(): return input().replace('\n', '') def ILCI(n: int): return [II() for _ in range(n)] def ILCF(n: int): return [IF() for _ in range(n)] def ILI(): return list(map(int, input().split())) def ILLI(n: int): return [[int(j) for j in input().split()] for i in range(n)] def ILF(): return list(map(float, input().split())) def ILLF(n: int): return [[float(j) for j in input().split()] for i in range(n)] def LTOS(lst: list, sep: str = ' '): return sep.join(map(str, lst)) def DEC(lst: list): return list(map(lambda x: x-1, lst)) def INC(lst: list): return list(map(lambda x: x+1, lst)) class LCA: def __init__(self, N: int) -> None: self.N = N self.to = [[] for _ in range(N)] self.co = [[] for _ in range(N)] self.dep = [0] * N self.costs = [0] * N l = 0 while (1 << l) < N: l += 1 self.l = l self.par = [([0]*l) for _ in range(N+1)] def add_edge(self, a: int, b: int, c = 0) -> None: self.to[a].append(b) self.co[a].append(c) self.to[b].append(a) self.co[b].append(c) def _dfs(self, v: int, d: int = 0, c = 0, p: int = -1) -> None: if p != -1: self.par[v][0] = p self.dep[v] = d self.costs[v] = c for i in range(len(self.to[v])): u = self.to[v][i] if u == p: continue else: self._dfs(u, d+1, c+self.co[v][i], v) def init(self, root: int = 0) -> None: self.root = root self._dfs(root) for i in range(self.l - 1): for v in range(self.N): self.par[v][i+1] = self.par[self.par[v][i]][i] #def __call__(self, a: int, b: int) -> int: def lcs(self, a: int, b: int) -> int: dep_s, dep_l = self.dep[a], self.dep[b] self_par = self.par if dep_s > dep_l: a, b = b, a dep_s, dep_l = dep_l, dep_s gap = dep_l - dep_s L_1 = self.l-1 for i in range(L_1, -1, -1): leng = 1 << i if gap >= leng: gap -= leng b = self_par[b][i] if a == b: return a for i in range(L_1, -1, -1): na = self_par[a][i] nb = self_par[b][i] if na != nb: a, b = na, nb return self_par[a][0] def length(self, a: int, b: int) -> int: #c = self.__call__(a, b) c = self.lcs(a, b) return self.dep[a] + self.dep[b] - self.dep[c] * 2 def dist(self, a: int, b: int): #c = self.__call__(a, b) c = self.lcs(a, b) return self.costs[a] + self.costs[b] - self.costs[c] * 2 def main(): N,Q = ILI() gr = LCA(N) es = [[] for _ in range(N)] for i in range(N-1): a,b, col, dist = ILI() a -= 1; b -= 1 es[a].append((b, dist, col)) es[b].append((a, dist, col)) gr.add_edge(a, b, dist) gr.init() ans = [0] * Q qs = [[] for _ in range(N)] for i in range(Q): cx,dy, a,b = ILI() a -= 1; b -= 1 #ans[i] = gr.dist(a, b) c = gr.lcs(a, b) ans[i] = gr.costs[a] + gr.costs[b] - gr.costs[c] * 2 qs[a].append((cx, i, 1, dy)) qs[b].append((cx, i, 1, dy)) qs[c].append((cx, i, -2, dy)) cnt = [0] * N sum_ = [0] * N def dfs(v: int, p: int = -1) -> None: for (col,qid,coeff,dist) in qs[v]: x = -sum_[col] x += dist * cnt[col] ans[qid] += x * coeff for (to, co, col) in es[v]: if to == p: continue cnt[col] += 1 sum_[col] += co dfs(to, v) cnt[col] -= 1 sum_[col] -= co dfs(0) for an in ans: print(an) if __name__ == '__main__': main() ```
instruction
0
53,711
13
107,422
Yes
output
1
53,711
13
107,423