message
stringlengths
2
49.9k
message_type
stringclasses
2 values
message_id
int64
0
1
conversation_id
int64
446
108k
cluster
float64
13
13
__index_level_0__
int64
892
217k
Provide tags and a correct Python 3 solution for this coding contest problem. Student Vladislav came to his programming exam completely unprepared as usual. He got a question about some strange algorithm on a graph β€” something that will definitely never be useful in real life. He asked a girl sitting next to him to lend him some cheat papers for this questions and found there the following definition: The minimum spanning tree T of graph G is such a tree that it contains all the vertices of the original graph G, and the sum of the weights of its edges is the minimum possible among all such trees. Vladislav drew a graph with n vertices and m edges containing no loops and multiple edges. He found one of its minimum spanning trees and then wrote for each edge its weight and whether it is included in the found tree or not. Unfortunately, the piece of paper where the graph was painted is gone and the teacher is getting very angry and demands to see the original graph. Help Vladislav come up with a graph so that the information about the minimum spanning tree remains correct. Input The first line of the input contains two integers n and m (<image>) β€” the number of vertices and the number of edges in the graph. Each of the next m lines describes an edge of the graph and consists of two integers aj and bj (1 ≀ aj ≀ 109, bj = {0, 1}). The first of these numbers is the weight of the edge and the second number is equal to 1 if this edge was included in the minimum spanning tree found by Vladislav, or 0 if it was not. It is guaranteed that exactly n - 1 number {bj} are equal to one and exactly m - n + 1 of them are equal to zero. Output If Vladislav has made a mistake and such graph doesn't exist, print - 1. Otherwise print m lines. On the j-th line print a pair of vertices (uj, vj) (1 ≀ uj, vj ≀ n, uj β‰  vj), that should be connected by the j-th edge. The edges are numbered in the same order as in the input. The graph, determined by these edges, must be connected, contain no loops or multiple edges and its edges with bj = 1 must define the minimum spanning tree. In case there are multiple possible solutions, print any of them. Examples Input 4 5 2 1 3 1 4 0 1 1 5 0 Output 2 4 1 4 3 4 3 1 3 2 Input 3 3 1 0 2 1 3 1 Output -1
instruction
0
40,052
13
80,104
Tags: constructive algorithms, data structures, graphs Correct Solution: ``` def graph(e): e = [(w, i, b) for i, (w, b) in enumerate(e)] e.sort() g = [None]*len(e) mst = [(w, i) for w, i, b in e if b] for n, (w, i) in enumerate(mst, 2): g[i] = 1, n cm = 0 available = [] for w, i, b in e: if not b: if not available: cm += 1 if mst[cm][0] > w: return None available = [(u, cm+2) for u in range(2, cm+2)] g[i] = available.pop() return g if __name__ == '__main__': n, m = map(int, input().split()) e = [] for _ in range(m): a, b = map(int, input().split()) e.append((a, b)) g = graph(e) if g: for u, v in g: print("{} {}".format(u, v)) else: print(-1) ```
output
1
40,052
13
80,105
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Student Vladislav came to his programming exam completely unprepared as usual. He got a question about some strange algorithm on a graph β€” something that will definitely never be useful in real life. He asked a girl sitting next to him to lend him some cheat papers for this questions and found there the following definition: The minimum spanning tree T of graph G is such a tree that it contains all the vertices of the original graph G, and the sum of the weights of its edges is the minimum possible among all such trees. Vladislav drew a graph with n vertices and m edges containing no loops and multiple edges. He found one of its minimum spanning trees and then wrote for each edge its weight and whether it is included in the found tree or not. Unfortunately, the piece of paper where the graph was painted is gone and the teacher is getting very angry and demands to see the original graph. Help Vladislav come up with a graph so that the information about the minimum spanning tree remains correct. Input The first line of the input contains two integers n and m (<image>) β€” the number of vertices and the number of edges in the graph. Each of the next m lines describes an edge of the graph and consists of two integers aj and bj (1 ≀ aj ≀ 109, bj = {0, 1}). The first of these numbers is the weight of the edge and the second number is equal to 1 if this edge was included in the minimum spanning tree found by Vladislav, or 0 if it was not. It is guaranteed that exactly n - 1 number {bj} are equal to one and exactly m - n + 1 of them are equal to zero. Output If Vladislav has made a mistake and such graph doesn't exist, print - 1. Otherwise print m lines. On the j-th line print a pair of vertices (uj, vj) (1 ≀ uj, vj ≀ n, uj β‰  vj), that should be connected by the j-th edge. The edges are numbered in the same order as in the input. The graph, determined by these edges, must be connected, contain no loops or multiple edges and its edges with bj = 1 must define the minimum spanning tree. In case there are multiple possible solutions, print any of them. Examples Input 4 5 2 1 3 1 4 0 1 1 5 0 Output 2 4 1 4 3 4 3 1 3 2 Input 3 3 1 0 2 1 3 1 Output -1 Submitted Solution: ``` def parse(i): t = input().split() return int(t[0]), int(t[1]), i n, m = [int(x) for x in input().split()] list = [parse(i) for i in range(m)] list.sort(key=lambda x: (x[0], -x[1])) # print(list) if list[0][1] == 0: print(-1) exit(0) for i in range(1, m): if i >= (n-1): break if list[i][1] == 0 and list[i-1][0] != list[i][0]: print(-1) exit(0) f = 0 t = 1 fakeFrom = 1 fakeTo = 2 graph = [] for i in range(m): if list[i][1] == 1: graph.append((f + 1, t + 1, list[i][2])) t += 1 else: graph.append((fakeFrom + 1, fakeTo + 1, list[i][2])) fakeFrom += 1 fakeTo += 1 # print(graph) graph.sort(key=lambda x: x[2]) for x in graph: print(x[0], x[1]) ```
instruction
0
40,053
13
80,106
No
output
1
40,053
13
80,107
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Student Vladislav came to his programming exam completely unprepared as usual. He got a question about some strange algorithm on a graph β€” something that will definitely never be useful in real life. He asked a girl sitting next to him to lend him some cheat papers for this questions and found there the following definition: The minimum spanning tree T of graph G is such a tree that it contains all the vertices of the original graph G, and the sum of the weights of its edges is the minimum possible among all such trees. Vladislav drew a graph with n vertices and m edges containing no loops and multiple edges. He found one of its minimum spanning trees and then wrote for each edge its weight and whether it is included in the found tree or not. Unfortunately, the piece of paper where the graph was painted is gone and the teacher is getting very angry and demands to see the original graph. Help Vladislav come up with a graph so that the information about the minimum spanning tree remains correct. Input The first line of the input contains two integers n and m (<image>) β€” the number of vertices and the number of edges in the graph. Each of the next m lines describes an edge of the graph and consists of two integers aj and bj (1 ≀ aj ≀ 109, bj = {0, 1}). The first of these numbers is the weight of the edge and the second number is equal to 1 if this edge was included in the minimum spanning tree found by Vladislav, or 0 if it was not. It is guaranteed that exactly n - 1 number {bj} are equal to one and exactly m - n + 1 of them are equal to zero. Output If Vladislav has made a mistake and such graph doesn't exist, print - 1. Otherwise print m lines. On the j-th line print a pair of vertices (uj, vj) (1 ≀ uj, vj ≀ n, uj β‰  vj), that should be connected by the j-th edge. The edges are numbered in the same order as in the input. The graph, determined by these edges, must be connected, contain no loops or multiple edges and its edges with bj = 1 must define the minimum spanning tree. In case there are multiple possible solutions, print any of them. Examples Input 4 5 2 1 3 1 4 0 1 1 5 0 Output 2 4 1 4 3 4 3 1 3 2 Input 3 3 1 0 2 1 3 1 Output -1 Submitted Solution: ``` def next(): global fr global to fr += 1 if fr == to: fr = 2 to += 1 n, m = tuple(map(int, input().split())) lenths = [] for i in range(m): a, b = tuple(map(int, input().split())) if b == 1: b = 0 else: b = 1 lenths.append((a, b)) res = [0] * m fr = 2 to = 3 my = 2 lenths.sort() f = 1 for i in range(m): if lenths[i][1] == 0: res[i] = (1, my) my += 1 else: if my * (my - 1) // 2 < to: f = 0 break res[i] = (fr, to) next() if f: for i in range(m): print(' '.join(list(map(str, res[i])))) else: print('-1') ```
instruction
0
40,054
13
80,108
No
output
1
40,054
13
80,109
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Student Vladislav came to his programming exam completely unprepared as usual. He got a question about some strange algorithm on a graph β€” something that will definitely never be useful in real life. He asked a girl sitting next to him to lend him some cheat papers for this questions and found there the following definition: The minimum spanning tree T of graph G is such a tree that it contains all the vertices of the original graph G, and the sum of the weights of its edges is the minimum possible among all such trees. Vladislav drew a graph with n vertices and m edges containing no loops and multiple edges. He found one of its minimum spanning trees and then wrote for each edge its weight and whether it is included in the found tree or not. Unfortunately, the piece of paper where the graph was painted is gone and the teacher is getting very angry and demands to see the original graph. Help Vladislav come up with a graph so that the information about the minimum spanning tree remains correct. Input The first line of the input contains two integers n and m (<image>) β€” the number of vertices and the number of edges in the graph. Each of the next m lines describes an edge of the graph and consists of two integers aj and bj (1 ≀ aj ≀ 109, bj = {0, 1}). The first of these numbers is the weight of the edge and the second number is equal to 1 if this edge was included in the minimum spanning tree found by Vladislav, or 0 if it was not. It is guaranteed that exactly n - 1 number {bj} are equal to one and exactly m - n + 1 of them are equal to zero. Output If Vladislav has made a mistake and such graph doesn't exist, print - 1. Otherwise print m lines. On the j-th line print a pair of vertices (uj, vj) (1 ≀ uj, vj ≀ n, uj β‰  vj), that should be connected by the j-th edge. The edges are numbered in the same order as in the input. The graph, determined by these edges, must be connected, contain no loops or multiple edges and its edges with bj = 1 must define the minimum spanning tree. In case there are multiple possible solutions, print any of them. Examples Input 4 5 2 1 3 1 4 0 1 1 5 0 Output 2 4 1 4 3 4 3 1 3 2 Input 3 3 1 0 2 1 3 1 Output -1 Submitted Solution: ``` __author__ = 'MoonBall' import sys # sys.stdin = open('data/D.in', 'r') T = 1 def process(): N, M = list(map(int, input().split())) e = [] for _ in range(M): e.append(list(map(int, input().split())) + [_]) e = sorted(e, key=lambda x: x[0]) ans = [0] * M # print(e) i = 3 j = 1 has = 1 ok = True for _e in e: if _e[1] == 1: has = has + 1 ans[_e[2]] = (has, has - 1) else: if has < i: ok = False else: ans[_e[2]] = (i, j) if j == i - 2: i = i + 1 j = 1 if not ok: print(-1) else: for u, v in ans: print(u, v) for _ in range(T): process() ```
instruction
0
40,055
13
80,110
No
output
1
40,055
13
80,111
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Student Vladislav came to his programming exam completely unprepared as usual. He got a question about some strange algorithm on a graph β€” something that will definitely never be useful in real life. He asked a girl sitting next to him to lend him some cheat papers for this questions and found there the following definition: The minimum spanning tree T of graph G is such a tree that it contains all the vertices of the original graph G, and the sum of the weights of its edges is the minimum possible among all such trees. Vladislav drew a graph with n vertices and m edges containing no loops and multiple edges. He found one of its minimum spanning trees and then wrote for each edge its weight and whether it is included in the found tree or not. Unfortunately, the piece of paper where the graph was painted is gone and the teacher is getting very angry and demands to see the original graph. Help Vladislav come up with a graph so that the information about the minimum spanning tree remains correct. Input The first line of the input contains two integers n and m (<image>) β€” the number of vertices and the number of edges in the graph. Each of the next m lines describes an edge of the graph and consists of two integers aj and bj (1 ≀ aj ≀ 109, bj = {0, 1}). The first of these numbers is the weight of the edge and the second number is equal to 1 if this edge was included in the minimum spanning tree found by Vladislav, or 0 if it was not. It is guaranteed that exactly n - 1 number {bj} are equal to one and exactly m - n + 1 of them are equal to zero. Output If Vladislav has made a mistake and such graph doesn't exist, print - 1. Otherwise print m lines. On the j-th line print a pair of vertices (uj, vj) (1 ≀ uj, vj ≀ n, uj β‰  vj), that should be connected by the j-th edge. The edges are numbered in the same order as in the input. The graph, determined by these edges, must be connected, contain no loops or multiple edges and its edges with bj = 1 must define the minimum spanning tree. In case there are multiple possible solutions, print any of them. Examples Input 4 5 2 1 3 1 4 0 1 1 5 0 Output 2 4 1 4 3 4 3 1 3 2 Input 3 3 1 0 2 1 3 1 Output -1 Submitted Solution: ``` def next(): global fr global to fr += 1 if fr == to: fr = 2 to += 1 n, m = tuple(map(int, input().split())) lenths = [] for i in range(m): a, b = tuple(map(int, input().split())) if b == 1: b = 0 else: b = 1 lenths.append((a, b, i)) res = [(0, 0)] * m fr = 2 to = 3 my = 0 len_sorted = sorted(lenths) f = 1 for i in range(m): #print(my, fr, to) if len_sorted[i][1] == 0: res[len_sorted[i][2]] = (1, my + 2) my += 1 else: if my * (my - 1) // 2 < to - 2: f = 0 break res[len_sorted[i][2]] = (fr, to) next() if my + 1 > n: f = 0 break if n == 448 and lenths[0][0] == 900058364: print(my, fr, to) if f: for i in range(m): print(' '.join(list(map(str, res[i])))) else: print('-1') ```
instruction
0
40,056
13
80,112
No
output
1
40,056
13
80,113
Provide tags and a correct Python 3 solution for this coding contest problem. A tree is an undirected connected graph without cycles. The distance between two vertices is the number of edges in a simple path between them. Limak is a little polar bear. He lives in a tree that consists of n vertices, numbered 1 through n. Limak recently learned how to jump. He can jump from a vertex to any vertex within distance at most k. For a pair of vertices (s, t) we define f(s, t) as the minimum number of jumps Limak needs to get from s to t. Your task is to find the sum of f(s, t) over all pairs of vertices (s, t) such that s < t. Input The first line of the input contains two integers n and k (2 ≀ n ≀ 200 000, 1 ≀ k ≀ 5) β€” the number of vertices in the tree and the maximum allowed jump distance respectively. The next n - 1 lines describe edges in the tree. The i-th of those lines contains two integers ai and bi (1 ≀ ai, bi ≀ n) β€” the indices on vertices connected with i-th edge. It's guaranteed that the given edges form a tree. Output Print one integer, denoting the sum of f(s, t) over all pairs of vertices (s, t) such that s < t. Examples Input 6 2 1 2 1 3 2 4 2 5 4 6 Output 20 Input 13 3 1 2 3 2 4 2 5 2 3 6 10 6 6 7 6 13 5 8 5 9 9 11 11 12 Output 114 Input 3 5 2 1 3 1 Output 3 Note In the first sample, the given tree has 6 vertices and it's displayed on the drawing below. Limak can jump to any vertex within distance at most 2. For example, from the vertex 5 he can jump to any of vertices: 1, 2 and 4 (well, he can also jump to the vertex 5 itself). <image> There are <image> pairs of vertices (s, t) such that s < t. For 5 of those pairs Limak would need two jumps: (1, 6), (3, 4), (3, 5), (3, 6), (5, 6). For other 10 pairs one jump is enough. So, the answer is 5Β·2 + 10Β·1 = 20. In the third sample, Limak can jump between every two vertices directly. There are 3 pairs of vertices (s < t), so the answer is 3Β·1 = 3.
instruction
0
40,088
13
80,176
Tags: dfs and similar, dp, trees Correct Solution: ``` import sys input = sys.stdin.buffer.readline from collections import deque n, k = map(int, input().split()) tot_dist = 0 vis = [0]*(n+1) dist = [[[0]*2 for j in range(k)] for i in range(n+1)] adj = [[]for i in range(n+1)] for i in range(n-1): u,v = map(int,input().split()) adj[u].append(v) adj[v].append(u) s = deque([1]) while s: c = s[-1] if not vis[c]: vis[c] = 1 for ne in adj[c]: if not vis[ne]: s.append(ne) else: # update dists via pairing paths at the current node tot = [0]*k sum_dist = 0 pairable = 0 for ne in adj[c]: # direct jumps of exactly k tot_dist += pairable * sum([dist[ne][i][0] for i in range(k)]) + \ sum_dist * sum([dist[ne][i][1] for i in range(k)]) # extra from remainder mod k for i in range(k): for j in range(k): tot_dist += (i+j+2+k-1)//k*dist[ne][i][1]*tot[j] # update pairable nodes for i in range(k): tot[i]+= dist[ne][i][1] pairable += dist[ne][i][1] sum_dist += dist[ne][i][0] # update paths for ne in adj[c]: for i in range(k): for j in range(2): dist[c][i][j] += dist[ne][(i+k-1)%k][j] dist[c][0][0] += dist[ne][k-1][1] dist[c][0][1] += 1 # update dists from path directly to current node for i in range(k): tot_dist += dist[c][i][0] + (i+k-1)//k * dist[c][i][1] s.pop() print(tot_dist) ```
output
1
40,088
13
80,177
Provide tags and a correct Python 3 solution for this coding contest problem. A tree is an undirected connected graph without cycles. The distance between two vertices is the number of edges in a simple path between them. Limak is a little polar bear. He lives in a tree that consists of n vertices, numbered 1 through n. Limak recently learned how to jump. He can jump from a vertex to any vertex within distance at most k. For a pair of vertices (s, t) we define f(s, t) as the minimum number of jumps Limak needs to get from s to t. Your task is to find the sum of f(s, t) over all pairs of vertices (s, t) such that s < t. Input The first line of the input contains two integers n and k (2 ≀ n ≀ 200 000, 1 ≀ k ≀ 5) β€” the number of vertices in the tree and the maximum allowed jump distance respectively. The next n - 1 lines describe edges in the tree. The i-th of those lines contains two integers ai and bi (1 ≀ ai, bi ≀ n) β€” the indices on vertices connected with i-th edge. It's guaranteed that the given edges form a tree. Output Print one integer, denoting the sum of f(s, t) over all pairs of vertices (s, t) such that s < t. Examples Input 6 2 1 2 1 3 2 4 2 5 4 6 Output 20 Input 13 3 1 2 3 2 4 2 5 2 3 6 10 6 6 7 6 13 5 8 5 9 9 11 11 12 Output 114 Input 3 5 2 1 3 1 Output 3 Note In the first sample, the given tree has 6 vertices and it's displayed on the drawing below. Limak can jump to any vertex within distance at most 2. For example, from the vertex 5 he can jump to any of vertices: 1, 2 and 4 (well, he can also jump to the vertex 5 itself). <image> There are <image> pairs of vertices (s, t) such that s < t. For 5 of those pairs Limak would need two jumps: (1, 6), (3, 4), (3, 5), (3, 6), (5, 6). For other 10 pairs one jump is enough. So, the answer is 5Β·2 + 10Β·1 = 20. In the third sample, Limak can jump between every two vertices directly. There are 3 pairs of vertices (s < t), so the answer is 3Β·1 = 3.
instruction
0
40,089
13
80,178
Tags: dfs and similar, dp, trees Correct Solution: ``` """ #If FastIO not needed, used this and don't forget to strip #import sys, math #input = sys.stdin.readline """ import os import sys from io import BytesIO, IOBase import heapq as h from bisect import bisect_left, bisect_right from types import GeneratorType BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): import os self.os = os 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 = self.os.read(self._fd, max(self.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 = self.os.read(self._fd, max(self.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: self.os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") from collections import defaultdict as dd, deque as dq, Counter as dc import math, string def getInts(): return [int(s) for s in input().split()] def getInt(): return int(input()) def getStrs(): return [s for s in input().split()] def getStr(): return input() def listStr(): return list(input()) def getMat(n): return [getInts() for _ in range(n)] MOD = 10**9+7 """ Each edge goes from parent U to child V Edge appears on S_V * (N - S_V) paths For each path of length L, (L + (-L)%K)/K L%K 0, 1, 2, 3, 4 (K - L%K)%K K K-1 K-2 ... 0 K-1 K-2 ... """ def bootstrap(f, stack=[]): def wrappedfunc(*args, **kwargs): if stack: return f(*args, **kwargs) else: to = f(*args, **kwargs) while True: if type(to) is GeneratorType: stack.append(to) to = next(to) else: stack.pop() if not stack: break to = stack[-1].send(to) return to return wrappedfunc def solve(): N, K = getInts() graph = dd(set) for i in range(N-1): A, B = getInts() graph[A].add(B) graph[B].add(A) dp_count = [[0 for j in range(5)] for i in range(N+1)] dp_total = [0 for j in range(N+1)] global ans ans = 0 @bootstrap def dfs(node,parent,depth): global ans dp_count[node][depth % K] = 1 dp_total[node] = 1 for neigh in graph[node]: if neigh != parent: yield dfs(neigh,node,depth+1) for i in range(K): for j in range(K): diff = (i+j-2*depth)%K req = (-diff)%K ans += req * dp_count[node][i] * dp_count[neigh][j] for i in range(K): dp_count[node][i] += dp_count[neigh][i] dp_total[node] += dp_total[neigh] ans += dp_total[node] * (N - dp_total[node]) yield dfs(1,-1,0) return ans//K print(solve()) ```
output
1
40,089
13
80,179
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A tree is an undirected connected graph without cycles. The distance between two vertices is the number of edges in a simple path between them. Limak is a little polar bear. He lives in a tree that consists of n vertices, numbered 1 through n. Limak recently learned how to jump. He can jump from a vertex to any vertex within distance at most k. For a pair of vertices (s, t) we define f(s, t) as the minimum number of jumps Limak needs to get from s to t. Your task is to find the sum of f(s, t) over all pairs of vertices (s, t) such that s < t. Input The first line of the input contains two integers n and k (2 ≀ n ≀ 200 000, 1 ≀ k ≀ 5) β€” the number of vertices in the tree and the maximum allowed jump distance respectively. The next n - 1 lines describe edges in the tree. The i-th of those lines contains two integers ai and bi (1 ≀ ai, bi ≀ n) β€” the indices on vertices connected with i-th edge. It's guaranteed that the given edges form a tree. Output Print one integer, denoting the sum of f(s, t) over all pairs of vertices (s, t) such that s < t. Examples Input 6 2 1 2 1 3 2 4 2 5 4 6 Output 20 Input 13 3 1 2 3 2 4 2 5 2 3 6 10 6 6 7 6 13 5 8 5 9 9 11 11 12 Output 114 Input 3 5 2 1 3 1 Output 3 Note In the first sample, the given tree has 6 vertices and it's displayed on the drawing below. Limak can jump to any vertex within distance at most 2. For example, from the vertex 5 he can jump to any of vertices: 1, 2 and 4 (well, he can also jump to the vertex 5 itself). <image> There are <image> pairs of vertices (s, t) such that s < t. For 5 of those pairs Limak would need two jumps: (1, 6), (3, 4), (3, 5), (3, 6), (5, 6). For other 10 pairs one jump is enough. So, the answer is 5Β·2 + 10Β·1 = 20. In the third sample, Limak can jump between every two vertices directly. There are 3 pairs of vertices (s < t), so the answer is 3Β·1 = 3. Submitted Solution: ``` a,b = map(int, input().split()) i=0 while a>0: a*=31 b*=2 i+=1 if a>b: print(i) break ```
instruction
0
40,090
13
80,180
No
output
1
40,090
13
80,181
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A tree is an undirected connected graph without cycles. The distance between two vertices is the number of edges in a simple path between them. Limak is a little polar bear. He lives in a tree that consists of n vertices, numbered 1 through n. Limak recently learned how to jump. He can jump from a vertex to any vertex within distance at most k. For a pair of vertices (s, t) we define f(s, t) as the minimum number of jumps Limak needs to get from s to t. Your task is to find the sum of f(s, t) over all pairs of vertices (s, t) such that s < t. Input The first line of the input contains two integers n and k (2 ≀ n ≀ 200 000, 1 ≀ k ≀ 5) β€” the number of vertices in the tree and the maximum allowed jump distance respectively. The next n - 1 lines describe edges in the tree. The i-th of those lines contains two integers ai and bi (1 ≀ ai, bi ≀ n) β€” the indices on vertices connected with i-th edge. It's guaranteed that the given edges form a tree. Output Print one integer, denoting the sum of f(s, t) over all pairs of vertices (s, t) such that s < t. Examples Input 6 2 1 2 1 3 2 4 2 5 4 6 Output 20 Input 13 3 1 2 3 2 4 2 5 2 3 6 10 6 6 7 6 13 5 8 5 9 9 11 11 12 Output 114 Input 3 5 2 1 3 1 Output 3 Note In the first sample, the given tree has 6 vertices and it's displayed on the drawing below. Limak can jump to any vertex within distance at most 2. For example, from the vertex 5 he can jump to any of vertices: 1, 2 and 4 (well, he can also jump to the vertex 5 itself). <image> There are <image> pairs of vertices (s, t) such that s < t. For 5 of those pairs Limak would need two jumps: (1, 6), (3, 4), (3, 5), (3, 6), (5, 6). For other 10 pairs one jump is enough. So, the answer is 5Β·2 + 10Β·1 = 20. In the third sample, Limak can jump between every two vertices directly. There are 3 pairs of vertices (s < t), so the answer is 3Β·1 = 3. Submitted Solution: ``` class UG: def __init__(self): self.V=0 self.E=0 self.adj=[] def build_graph(self,v): self.V=v self.E=0 for i in range(v): self.adj.append([]) def Vertices(self): return self.V def Edges(self): return self.E def addEdge(self,v,w): self.adj[v].insert(0,w) self.adj[w].insert(0,v) def adj_vertices(self,v): return self.adj[v] class BFS: def __init__(self,graph,s): self.marked=[False]*graph.Vertices() self.edgeTo=[None]*graph.Vertices() self.distTo=[1000000000]*graph.Vertices() self.s=s self.bfs(graph,s) def bfs(self,graph,s): queue=[] self.marked[s]=True self.distTo[s]=0 queue.append(s) while(queue): v=queue.pop(0) for w in graph.adj_vertices(v): if(not self.marked[w]): #print(w) self.edgeTo[w]=v self.marked[w]=True self.distTo[w]=self.distTo[v]+1 queue.append(w) def dist(self,t,k): if(not self.marked[t]): return 0 if(self.distTo[t]>k): return (self.distTo[t]//k)+(self.distTo[t]%k) return 1 v,k=[int(x) for x in input().split()] ug=UG() ug.build_graph(v) for i in range(v-1): x,y=[int(x)-1 for x in input().split()] ug.addEdge(x,y) dist=0 #print(ug.adj) #print(ug.distTo) for i in range(ug.Vertices()): bfs=BFS(ug,i) #print(bfs.distTo) for j in range(i+1,ug.Vertices()): if(i!=j and i<j): #print(i+1,"->",j+1,"=",bfs.dist(j,k)) dist+=bfs.dist(j,k) print(dist) ```
instruction
0
40,091
13
80,182
No
output
1
40,091
13
80,183
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A tree is an undirected connected graph without cycles. The distance between two vertices is the number of edges in a simple path between them. Limak is a little polar bear. He lives in a tree that consists of n vertices, numbered 1 through n. Limak recently learned how to jump. He can jump from a vertex to any vertex within distance at most k. For a pair of vertices (s, t) we define f(s, t) as the minimum number of jumps Limak needs to get from s to t. Your task is to find the sum of f(s, t) over all pairs of vertices (s, t) such that s < t. Input The first line of the input contains two integers n and k (2 ≀ n ≀ 200 000, 1 ≀ k ≀ 5) β€” the number of vertices in the tree and the maximum allowed jump distance respectively. The next n - 1 lines describe edges in the tree. The i-th of those lines contains two integers ai and bi (1 ≀ ai, bi ≀ n) β€” the indices on vertices connected with i-th edge. It's guaranteed that the given edges form a tree. Output Print one integer, denoting the sum of f(s, t) over all pairs of vertices (s, t) such that s < t. Examples Input 6 2 1 2 1 3 2 4 2 5 4 6 Output 20 Input 13 3 1 2 3 2 4 2 5 2 3 6 10 6 6 7 6 13 5 8 5 9 9 11 11 12 Output 114 Input 3 5 2 1 3 1 Output 3 Note In the first sample, the given tree has 6 vertices and it's displayed on the drawing below. Limak can jump to any vertex within distance at most 2. For example, from the vertex 5 he can jump to any of vertices: 1, 2 and 4 (well, he can also jump to the vertex 5 itself). <image> There are <image> pairs of vertices (s, t) such that s < t. For 5 of those pairs Limak would need two jumps: (1, 6), (3, 4), (3, 5), (3, 6), (5, 6). For other 10 pairs one jump is enough. So, the answer is 5Β·2 + 10Β·1 = 20. In the third sample, Limak can jump between every two vertices directly. There are 3 pairs of vertices (s < t), so the answer is 3Β·1 = 3. Submitted Solution: ``` a,b = map(int, input().split()) i=0 while a>0: a*=3 b*=2 i+=1 if a>b: print(i) break ```
instruction
0
40,092
13
80,184
No
output
1
40,092
13
80,185
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A tree is an undirected connected graph without cycles. The distance between two vertices is the number of edges in a simple path between them. Limak is a little polar bear. He lives in a tree that consists of n vertices, numbered 1 through n. Limak recently learned how to jump. He can jump from a vertex to any vertex within distance at most k. For a pair of vertices (s, t) we define f(s, t) as the minimum number of jumps Limak needs to get from s to t. Your task is to find the sum of f(s, t) over all pairs of vertices (s, t) such that s < t. Input The first line of the input contains two integers n and k (2 ≀ n ≀ 200 000, 1 ≀ k ≀ 5) β€” the number of vertices in the tree and the maximum allowed jump distance respectively. The next n - 1 lines describe edges in the tree. The i-th of those lines contains two integers ai and bi (1 ≀ ai, bi ≀ n) β€” the indices on vertices connected with i-th edge. It's guaranteed that the given edges form a tree. Output Print one integer, denoting the sum of f(s, t) over all pairs of vertices (s, t) such that s < t. Examples Input 6 2 1 2 1 3 2 4 2 5 4 6 Output 20 Input 13 3 1 2 3 2 4 2 5 2 3 6 10 6 6 7 6 13 5 8 5 9 9 11 11 12 Output 114 Input 3 5 2 1 3 1 Output 3 Note In the first sample, the given tree has 6 vertices and it's displayed on the drawing below. Limak can jump to any vertex within distance at most 2. For example, from the vertex 5 he can jump to any of vertices: 1, 2 and 4 (well, he can also jump to the vertex 5 itself). <image> There are <image> pairs of vertices (s, t) such that s < t. For 5 of those pairs Limak would need two jumps: (1, 6), (3, 4), (3, 5), (3, 6), (5, 6). For other 10 pairs one jump is enough. So, the answer is 5Β·2 + 10Β·1 = 20. In the third sample, Limak can jump between every two vertices directly. There are 3 pairs of vertices (s < t), so the answer is 3Β·1 = 3. Submitted Solution: ``` import math #n=int(input()) # arr=list(map(int,input().strip().split())) n,skip=list(map(int,input().strip().split())) graph=[[2000 for i in range(n)] for j in range(n)] for _ in range(n-1): n1,n2=list(map(int,input().strip().split())) graph[n1-1][n2-1]=1 graph[n2-1][n1-1] = 1 for i in range(n): for j in range(n): for k in range(n): if graph[i][j]>graph[i][k]+graph[k][j]: graph[i][j] = graph[i][k] + graph[k][j] res=0 for i in range(n-1): for j in range(i+1,n): res+=math.ceil(graph[i][j]/skip) #print(graph[i][j],skip,math.ceil(graph[i][j]/skip)) print(res) ```
instruction
0
40,093
13
80,186
No
output
1
40,093
13
80,187
Provide tags and a correct Python 3 solution for this coding contest problem. The [BFS](https://en.wikipedia.org/wiki/Breadth-first_search) algorithm is defined as follows. 1. Consider an undirected graph with vertices numbered from 1 to n. Initialize q as a new [queue](http://gg.gg/queue_en) containing only vertex 1, mark the vertex 1 as used. 2. Extract a vertex v from the head of the queue q. 3. Print the index of vertex v. 4. Iterate in arbitrary order through all such vertices u that u is a neighbor of v and is not marked yet as used. Mark the vertex u as used and insert it into the tail of the queue q. 5. If the queue is not empty, continue from step 2. 6. Otherwise finish. Since the order of choosing neighbors of each vertex can vary, it turns out that there may be multiple sequences which BFS can print. In this problem you need to check whether a given sequence corresponds to some valid BFS traversal of the given tree starting from vertex 1. The [tree](http://gg.gg/tree_en) is an undirected graph, such that there is exactly one simple path between any two vertices. Input The first line contains a single integer n (1 ≀ n ≀ 2 β‹… 10^5) which denotes the number of nodes in the tree. The following n - 1 lines describe the edges of the tree. Each of them contains two integers x and y (1 ≀ x, y ≀ n) β€” the endpoints of the corresponding edge of the tree. It is guaranteed that the given graph is a tree. The last line contains n distinct integers a_1, a_2, …, a_n (1 ≀ a_i ≀ n) β€” the sequence to check. Output Print "Yes" (quotes for clarity) if the sequence corresponds to some valid BFS traversal of the given tree and "No" (quotes for clarity) otherwise. You can print each letter in any case (upper or lower). Examples Input 4 1 2 1 3 2 4 1 2 3 4 Output Yes Input 4 1 2 1 3 2 4 1 2 4 3 Output No Note Both sample tests have the same tree in them. In this tree, there are two valid BFS orderings: * 1, 2, 3, 4, * 1, 3, 2, 4. The ordering 1, 2, 4, 3 doesn't correspond to any valid BFS order.
instruction
0
40,429
13
80,858
Tags: dfs and similar, graphs, shortest paths, trees Correct Solution: ``` n = int(input()) d = {} for i in range(n-1): u,v = map(int,input().split()) try: d[u].append(v) except: d[u] = [v] try: d[v].append(u) except: d[v] = [u] l = list(map(int,input().split())) f = 0 i = 0 j = 1 while i < n and j < n: if l[i] not in d[l[j]]: i = i + 1 else: j = j + 1 if j != n or l[0] != 1: print("No") else: print("Yes") ```
output
1
40,429
13
80,859
Provide tags and a correct Python 3 solution for this coding contest problem. The [BFS](https://en.wikipedia.org/wiki/Breadth-first_search) algorithm is defined as follows. 1. Consider an undirected graph with vertices numbered from 1 to n. Initialize q as a new [queue](http://gg.gg/queue_en) containing only vertex 1, mark the vertex 1 as used. 2. Extract a vertex v from the head of the queue q. 3. Print the index of vertex v. 4. Iterate in arbitrary order through all such vertices u that u is a neighbor of v and is not marked yet as used. Mark the vertex u as used and insert it into the tail of the queue q. 5. If the queue is not empty, continue from step 2. 6. Otherwise finish. Since the order of choosing neighbors of each vertex can vary, it turns out that there may be multiple sequences which BFS can print. In this problem you need to check whether a given sequence corresponds to some valid BFS traversal of the given tree starting from vertex 1. The [tree](http://gg.gg/tree_en) is an undirected graph, such that there is exactly one simple path between any two vertices. Input The first line contains a single integer n (1 ≀ n ≀ 2 β‹… 10^5) which denotes the number of nodes in the tree. The following n - 1 lines describe the edges of the tree. Each of them contains two integers x and y (1 ≀ x, y ≀ n) β€” the endpoints of the corresponding edge of the tree. It is guaranteed that the given graph is a tree. The last line contains n distinct integers a_1, a_2, …, a_n (1 ≀ a_i ≀ n) β€” the sequence to check. Output Print "Yes" (quotes for clarity) if the sequence corresponds to some valid BFS traversal of the given tree and "No" (quotes for clarity) otherwise. You can print each letter in any case (upper or lower). Examples Input 4 1 2 1 3 2 4 1 2 3 4 Output Yes Input 4 1 2 1 3 2 4 1 2 4 3 Output No Note Both sample tests have the same tree in them. In this tree, there are two valid BFS orderings: * 1, 2, 3, 4, * 1, 3, 2, 4. The ordering 1, 2, 4, 3 doesn't correspond to any valid BFS order.
instruction
0
40,430
13
80,860
Tags: dfs and similar, graphs, shortest paths, trees Correct Solution: ``` import sys from collections import defaultdict def out(s):return sys.stdout.write(s) n=int(sys.stdin.readline()) dic = defaultdict(set) for i in range(n-1): a,b=map(int,sys.stdin.readline().split()) dic[a].add(b) dic[b].add(a) c=list(map(int,sys.stdin.readline().split())) if c[0]!=1: out("No") else: i =1 j =0 while i<n and j<n: if c[i] not in dic[c[j]]: j+=1 else: i+=1 if i==n: out("Yes") else: out("No") ```
output
1
40,430
13
80,861
Provide tags and a correct Python 3 solution for this coding contest problem. The [BFS](https://en.wikipedia.org/wiki/Breadth-first_search) algorithm is defined as follows. 1. Consider an undirected graph with vertices numbered from 1 to n. Initialize q as a new [queue](http://gg.gg/queue_en) containing only vertex 1, mark the vertex 1 as used. 2. Extract a vertex v from the head of the queue q. 3. Print the index of vertex v. 4. Iterate in arbitrary order through all such vertices u that u is a neighbor of v and is not marked yet as used. Mark the vertex u as used and insert it into the tail of the queue q. 5. If the queue is not empty, continue from step 2. 6. Otherwise finish. Since the order of choosing neighbors of each vertex can vary, it turns out that there may be multiple sequences which BFS can print. In this problem you need to check whether a given sequence corresponds to some valid BFS traversal of the given tree starting from vertex 1. The [tree](http://gg.gg/tree_en) is an undirected graph, such that there is exactly one simple path between any two vertices. Input The first line contains a single integer n (1 ≀ n ≀ 2 β‹… 10^5) which denotes the number of nodes in the tree. The following n - 1 lines describe the edges of the tree. Each of them contains two integers x and y (1 ≀ x, y ≀ n) β€” the endpoints of the corresponding edge of the tree. It is guaranteed that the given graph is a tree. The last line contains n distinct integers a_1, a_2, …, a_n (1 ≀ a_i ≀ n) β€” the sequence to check. Output Print "Yes" (quotes for clarity) if the sequence corresponds to some valid BFS traversal of the given tree and "No" (quotes for clarity) otherwise. You can print each letter in any case (upper or lower). Examples Input 4 1 2 1 3 2 4 1 2 3 4 Output Yes Input 4 1 2 1 3 2 4 1 2 4 3 Output No Note Both sample tests have the same tree in them. In this tree, there are two valid BFS orderings: * 1, 2, 3, 4, * 1, 3, 2, 4. The ordering 1, 2, 4, 3 doesn't correspond to any valid BFS order.
instruction
0
40,431
13
80,862
Tags: dfs and similar, graphs, shortest paths, trees Correct Solution: ``` import sys from array import array # noqa: F401 from collections import deque def input(): return sys.stdin.buffer.readline().decode('utf-8') n = int(input()) adj = [[] for _ in range(n)] for u, v in (map(int, input().split()) for _ in range(n - 1)): adj[u - 1].append(v - 1) adj[v - 1].append(u - 1) a = list(map(lambda x: int(x) - 1, input().split())) priority = [0] * n for i, x in enumerate(a): priority[x] = i dq = deque([(0, -1)]) ans = [] while dq: v, par = dq.popleft() ans.append(v) adj[v].sort(key=lambda i: priority[i]) for dest in adj[v]: if dest == par: continue dq.append((dest, v)) print(*ans, file=sys.stderr) print('Yes' if a == ans else 'No') ```
output
1
40,431
13
80,863
Provide tags and a correct Python 3 solution for this coding contest problem. The [BFS](https://en.wikipedia.org/wiki/Breadth-first_search) algorithm is defined as follows. 1. Consider an undirected graph with vertices numbered from 1 to n. Initialize q as a new [queue](http://gg.gg/queue_en) containing only vertex 1, mark the vertex 1 as used. 2. Extract a vertex v from the head of the queue q. 3. Print the index of vertex v. 4. Iterate in arbitrary order through all such vertices u that u is a neighbor of v and is not marked yet as used. Mark the vertex u as used and insert it into the tail of the queue q. 5. If the queue is not empty, continue from step 2. 6. Otherwise finish. Since the order of choosing neighbors of each vertex can vary, it turns out that there may be multiple sequences which BFS can print. In this problem you need to check whether a given sequence corresponds to some valid BFS traversal of the given tree starting from vertex 1. The [tree](http://gg.gg/tree_en) is an undirected graph, such that there is exactly one simple path between any two vertices. Input The first line contains a single integer n (1 ≀ n ≀ 2 β‹… 10^5) which denotes the number of nodes in the tree. The following n - 1 lines describe the edges of the tree. Each of them contains two integers x and y (1 ≀ x, y ≀ n) β€” the endpoints of the corresponding edge of the tree. It is guaranteed that the given graph is a tree. The last line contains n distinct integers a_1, a_2, …, a_n (1 ≀ a_i ≀ n) β€” the sequence to check. Output Print "Yes" (quotes for clarity) if the sequence corresponds to some valid BFS traversal of the given tree and "No" (quotes for clarity) otherwise. You can print each letter in any case (upper or lower). Examples Input 4 1 2 1 3 2 4 1 2 3 4 Output Yes Input 4 1 2 1 3 2 4 1 2 4 3 Output No Note Both sample tests have the same tree in them. In this tree, there are two valid BFS orderings: * 1, 2, 3, 4, * 1, 3, 2, 4. The ordering 1, 2, 4, 3 doesn't correspond to any valid BFS order.
instruction
0
40,432
13
80,864
Tags: dfs and similar, graphs, shortest paths, trees Correct Solution: ``` import math,sys from collections import Counter,defaultdict def li(): return list(map(int,sys.stdin.readline().split())) def ls(): return list(map(int,list(input()))) def la(): return list(input()) def ii(): return int(input()) def dic(x): return defaultdict(lambda: x) def isPrime(n): i= 2 if n == 1: return False while i <= int(math.sqrt(n)): if n%i == 0: return False i = i + 1 return True def gcd(a,b): if b == 0: return a return gcd(b,a%b) def binarySearch(arr, x): l,r = 0,len(arr)-1 while l <= r: mid = l + (r - l) // 2; if arr[mid] == x: return True elif arr[mid] < x: l = mid + 1 else: r = mid - 1 return False n = ii() g = defaultdict(set) for _ in range(n-1): x,y = li() g[x].add(y) g[y].add(x) a = li() j = 0 flag = 0 if a[j] == 1: i = 1 while i < n and j<n: if a[i] not in g[a[j]]: j= j + 1 else: i = i +1 if i ==n : print('Yes') else : print('No') else: print('No') ```
output
1
40,432
13
80,865
Provide tags and a correct Python 3 solution for this coding contest problem. The [BFS](https://en.wikipedia.org/wiki/Breadth-first_search) algorithm is defined as follows. 1. Consider an undirected graph with vertices numbered from 1 to n. Initialize q as a new [queue](http://gg.gg/queue_en) containing only vertex 1, mark the vertex 1 as used. 2. Extract a vertex v from the head of the queue q. 3. Print the index of vertex v. 4. Iterate in arbitrary order through all such vertices u that u is a neighbor of v and is not marked yet as used. Mark the vertex u as used and insert it into the tail of the queue q. 5. If the queue is not empty, continue from step 2. 6. Otherwise finish. Since the order of choosing neighbors of each vertex can vary, it turns out that there may be multiple sequences which BFS can print. In this problem you need to check whether a given sequence corresponds to some valid BFS traversal of the given tree starting from vertex 1. The [tree](http://gg.gg/tree_en) is an undirected graph, such that there is exactly one simple path between any two vertices. Input The first line contains a single integer n (1 ≀ n ≀ 2 β‹… 10^5) which denotes the number of nodes in the tree. The following n - 1 lines describe the edges of the tree. Each of them contains two integers x and y (1 ≀ x, y ≀ n) β€” the endpoints of the corresponding edge of the tree. It is guaranteed that the given graph is a tree. The last line contains n distinct integers a_1, a_2, …, a_n (1 ≀ a_i ≀ n) β€” the sequence to check. Output Print "Yes" (quotes for clarity) if the sequence corresponds to some valid BFS traversal of the given tree and "No" (quotes for clarity) otherwise. You can print each letter in any case (upper or lower). Examples Input 4 1 2 1 3 2 4 1 2 3 4 Output Yes Input 4 1 2 1 3 2 4 1 2 4 3 Output No Note Both sample tests have the same tree in them. In this tree, there are two valid BFS orderings: * 1, 2, 3, 4, * 1, 3, 2, 4. The ordering 1, 2, 4, 3 doesn't correspond to any valid BFS order.
instruction
0
40,433
13
80,866
Tags: dfs and similar, graphs, shortest paths, trees Correct Solution: ``` """ We can store the neighbors of the nodes in their adjacency lists. After that, we can sort the adjacency lists of all the nodes in the order in which they are present in the input BFS Sequence. Now we can do the standard BFS traversal starting from node 1 and check if this BFS traversal is same as the input BFS Sequence. If its not, the answer will be "No". """ from collections import defaultdict, deque n = int(input()) pairs = defaultdict(set) pairs[0].add(1) pairs[1].add(0) for i in range(n - 1): x, y = map(int, input().split()) pairs[x].add(y) pairs[y].add(x) a = list(map(int, input().split())) q = deque() q.append(0) i = 0 par = [0] * (n + 1) while len(q): v = q.popleft() pairs[v].discard(par[v]) l = len(pairs[v]) if pairs[v] != set(a[i:i + l]): print('No') break for j in range(i, i + l): q.append(a[j]) par[a[j]] = v i += l else: print('Yes') ```
output
1
40,433
13
80,867
Provide tags and a correct Python 3 solution for this coding contest problem. The [BFS](https://en.wikipedia.org/wiki/Breadth-first_search) algorithm is defined as follows. 1. Consider an undirected graph with vertices numbered from 1 to n. Initialize q as a new [queue](http://gg.gg/queue_en) containing only vertex 1, mark the vertex 1 as used. 2. Extract a vertex v from the head of the queue q. 3. Print the index of vertex v. 4. Iterate in arbitrary order through all such vertices u that u is a neighbor of v and is not marked yet as used. Mark the vertex u as used and insert it into the tail of the queue q. 5. If the queue is not empty, continue from step 2. 6. Otherwise finish. Since the order of choosing neighbors of each vertex can vary, it turns out that there may be multiple sequences which BFS can print. In this problem you need to check whether a given sequence corresponds to some valid BFS traversal of the given tree starting from vertex 1. The [tree](http://gg.gg/tree_en) is an undirected graph, such that there is exactly one simple path between any two vertices. Input The first line contains a single integer n (1 ≀ n ≀ 2 β‹… 10^5) which denotes the number of nodes in the tree. The following n - 1 lines describe the edges of the tree. Each of them contains two integers x and y (1 ≀ x, y ≀ n) β€” the endpoints of the corresponding edge of the tree. It is guaranteed that the given graph is a tree. The last line contains n distinct integers a_1, a_2, …, a_n (1 ≀ a_i ≀ n) β€” the sequence to check. Output Print "Yes" (quotes for clarity) if the sequence corresponds to some valid BFS traversal of the given tree and "No" (quotes for clarity) otherwise. You can print each letter in any case (upper or lower). Examples Input 4 1 2 1 3 2 4 1 2 3 4 Output Yes Input 4 1 2 1 3 2 4 1 2 4 3 Output No Note Both sample tests have the same tree in them. In this tree, there are two valid BFS orderings: * 1, 2, 3, 4, * 1, 3, 2, 4. The ordering 1, 2, 4, 3 doesn't correspond to any valid BFS order.
instruction
0
40,434
13
80,868
Tags: dfs and similar, graphs, shortest paths, trees Correct Solution: ``` from collections import deque n = int(input()) graph = [set()for i in range(n+1)] for i in range(n-1): x,y =map(int,input().split()) graph[x].add(y) graph[y].add(x) l = list(map(int,input().split())) if(l[0]!=1): print('No') exit() i=1 j=0 while(i< n and j < n): if(l[i] in graph[l[j]]): i+=1 else: j+=1 if(i==n): print("Yes") else: print('No') ```
output
1
40,434
13
80,869
Provide tags and a correct Python 3 solution for this coding contest problem. The [BFS](https://en.wikipedia.org/wiki/Breadth-first_search) algorithm is defined as follows. 1. Consider an undirected graph with vertices numbered from 1 to n. Initialize q as a new [queue](http://gg.gg/queue_en) containing only vertex 1, mark the vertex 1 as used. 2. Extract a vertex v from the head of the queue q. 3. Print the index of vertex v. 4. Iterate in arbitrary order through all such vertices u that u is a neighbor of v and is not marked yet as used. Mark the vertex u as used and insert it into the tail of the queue q. 5. If the queue is not empty, continue from step 2. 6. Otherwise finish. Since the order of choosing neighbors of each vertex can vary, it turns out that there may be multiple sequences which BFS can print. In this problem you need to check whether a given sequence corresponds to some valid BFS traversal of the given tree starting from vertex 1. The [tree](http://gg.gg/tree_en) is an undirected graph, such that there is exactly one simple path between any two vertices. Input The first line contains a single integer n (1 ≀ n ≀ 2 β‹… 10^5) which denotes the number of nodes in the tree. The following n - 1 lines describe the edges of the tree. Each of them contains two integers x and y (1 ≀ x, y ≀ n) β€” the endpoints of the corresponding edge of the tree. It is guaranteed that the given graph is a tree. The last line contains n distinct integers a_1, a_2, …, a_n (1 ≀ a_i ≀ n) β€” the sequence to check. Output Print "Yes" (quotes for clarity) if the sequence corresponds to some valid BFS traversal of the given tree and "No" (quotes for clarity) otherwise. You can print each letter in any case (upper or lower). Examples Input 4 1 2 1 3 2 4 1 2 3 4 Output Yes Input 4 1 2 1 3 2 4 1 2 4 3 Output No Note Both sample tests have the same tree in them. In this tree, there are two valid BFS orderings: * 1, 2, 3, 4, * 1, 3, 2, 4. The ordering 1, 2, 4, 3 doesn't correspond to any valid BFS order.
instruction
0
40,435
13
80,870
Tags: dfs and similar, graphs, shortest paths, trees Correct Solution: ``` n = int(input()) d = {} for i in range(n-1): a,b = map(int,input().split()) try: d[a].append(b); except: d[a] = [b] try: d[b].append(a); except: d[b] = [a] array = list(map(int,input().split())) flag=0; if array[0]==1: i = 1; j = 0; while ( j < n and i < n ): if ( array[j] in d[array[i]] ): i+=1; else: j+=1; if j==n and i!=n: flag=1; else: flag=1; if flag==1: print("No") else: print("Yes") ```
output
1
40,435
13
80,871
Provide tags and a correct Python 3 solution for this coding contest problem. The [BFS](https://en.wikipedia.org/wiki/Breadth-first_search) algorithm is defined as follows. 1. Consider an undirected graph with vertices numbered from 1 to n. Initialize q as a new [queue](http://gg.gg/queue_en) containing only vertex 1, mark the vertex 1 as used. 2. Extract a vertex v from the head of the queue q. 3. Print the index of vertex v. 4. Iterate in arbitrary order through all such vertices u that u is a neighbor of v and is not marked yet as used. Mark the vertex u as used and insert it into the tail of the queue q. 5. If the queue is not empty, continue from step 2. 6. Otherwise finish. Since the order of choosing neighbors of each vertex can vary, it turns out that there may be multiple sequences which BFS can print. In this problem you need to check whether a given sequence corresponds to some valid BFS traversal of the given tree starting from vertex 1. The [tree](http://gg.gg/tree_en) is an undirected graph, such that there is exactly one simple path between any two vertices. Input The first line contains a single integer n (1 ≀ n ≀ 2 β‹… 10^5) which denotes the number of nodes in the tree. The following n - 1 lines describe the edges of the tree. Each of them contains two integers x and y (1 ≀ x, y ≀ n) β€” the endpoints of the corresponding edge of the tree. It is guaranteed that the given graph is a tree. The last line contains n distinct integers a_1, a_2, …, a_n (1 ≀ a_i ≀ n) β€” the sequence to check. Output Print "Yes" (quotes for clarity) if the sequence corresponds to some valid BFS traversal of the given tree and "No" (quotes for clarity) otherwise. You can print each letter in any case (upper or lower). Examples Input 4 1 2 1 3 2 4 1 2 3 4 Output Yes Input 4 1 2 1 3 2 4 1 2 4 3 Output No Note Both sample tests have the same tree in them. In this tree, there are two valid BFS orderings: * 1, 2, 3, 4, * 1, 3, 2, 4. The ordering 1, 2, 4, 3 doesn't correspond to any valid BFS order.
instruction
0
40,436
13
80,872
Tags: dfs and similar, graphs, shortest paths, trees Correct Solution: ``` import sys, os, io def rs(): return sys.stdin.readline().rstrip() def ri(): return int(sys.stdin.readline()) def ria(): return list(map(int, sys.stdin.readline().split())) def ws(s): sys.stdout.write(s + '\n') def wi(n): sys.stdout.write(str(n) + '\n') def wia(a): sys.stdout.write(' '.join([str(x) for x in a]) + '\n') import math,datetime,functools,itertools,operator,bisect,fractions,statistics from collections import deque,defaultdict,OrderedDict,Counter from fractions import Fraction from decimal import Decimal from sys import stdout from heapq import heappush, heappop, heapify ,_heapify_max,_heappop_max,nsmallest,nlargest # sys.setrecursionlimit(111111) INF=999999999999999999999999 alphabets="abcdefghijklmnopqrstuvwxyz" class SortedList: def __init__(self, iterable=[], _load=200): """Initialize sorted list instance.""" values = sorted(iterable) self._len = _len = len(values) self._load = _load self._lists = _lists = [values[i:i + _load] for i in range(0, _len, _load)] self._list_lens = [len(_list) for _list in _lists] self._mins = [_list[0] for _list in _lists] self._fen_tree = [] self._rebuild = True def _fen_build(self): """Build a fenwick tree instance.""" self._fen_tree[:] = self._list_lens _fen_tree = self._fen_tree for i in range(len(_fen_tree)): if i | i + 1 < len(_fen_tree): _fen_tree[i | i + 1] += _fen_tree[i] self._rebuild = False def _fen_update(self, index, value): """Update `fen_tree[index] += value`.""" if not self._rebuild: _fen_tree = self._fen_tree while index < len(_fen_tree): _fen_tree[index] += value index |= index + 1 def _fen_query(self, end): """Return `sum(_fen_tree[:end])`.""" if self._rebuild: self._fen_build() _fen_tree = self._fen_tree x = 0 while end: x += _fen_tree[end - 1] end &= end - 1 return x def _fen_findkth(self, k): """Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`).""" _list_lens = self._list_lens if k < _list_lens[0]: return 0, k if k >= self._len - _list_lens[-1]: return len(_list_lens) - 1, k + _list_lens[-1] - self._len if self._rebuild: self._fen_build() _fen_tree = self._fen_tree idx = -1 for d in reversed(range(len(_fen_tree).bit_length())): right_idx = idx + (1 << d) if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]: idx = right_idx k -= _fen_tree[idx] return idx + 1, k def _delete(self, pos, idx): """Delete value at the given `(pos, idx)`.""" _lists = self._lists _mins = self._mins _list_lens = self._list_lens self._len -= 1 self._fen_update(pos, -1) del _lists[pos][idx] _list_lens[pos] -= 1 if _list_lens[pos]: _mins[pos] = _lists[pos][0] else: del _lists[pos] del _list_lens[pos] del _mins[pos] self._rebuild = True def _loc_left(self, value): """Return an index pair that corresponds to the first position of `value` in the sorted list.""" if not self._len: return 0, 0 _lists = self._lists _mins = self._mins lo, pos = -1, len(_lists) - 1 while lo + 1 < pos: mi = (lo + pos) >> 1 if value <= _mins[mi]: pos = mi else: lo = mi if pos and value <= _lists[pos - 1][-1]: pos -= 1 _list = _lists[pos] lo, idx = -1, len(_list) while lo + 1 < idx: mi = (lo + idx) >> 1 if value <= _list[mi]: idx = mi else: lo = mi return pos, idx def _loc_right(self, value): """Return an index pair that corresponds to the last position of `value` in the sorted list.""" if not self._len: return 0, 0 _lists = self._lists _mins = self._mins pos, hi = 0, len(_lists) while pos + 1 < hi: mi = (pos + hi) >> 1 if value < _mins[mi]: hi = mi else: pos = mi _list = _lists[pos] lo, idx = -1, len(_list) while lo + 1 < idx: mi = (lo + idx) >> 1 if value < _list[mi]: idx = mi else: lo = mi return pos, idx def add(self, value): """Add `value` to sorted list.""" _load = self._load _lists = self._lists _mins = self._mins _list_lens = self._list_lens self._len += 1 if _lists: pos, idx = self._loc_right(value) self._fen_update(pos, 1) _list = _lists[pos] _list.insert(idx, value) _list_lens[pos] += 1 _mins[pos] = _list[0] if _load + _load < len(_list): _lists.insert(pos + 1, _list[_load:]) _list_lens.insert(pos + 1, len(_list) - _load) _mins.insert(pos + 1, _list[_load]) _list_lens[pos] = _load del _list[_load:] self._rebuild = True else: _lists.append([value]) _mins.append(value) _list_lens.append(1) self._rebuild = True def discard(self, value): """Remove `value` from sorted list if it is a member.""" _lists = self._lists if _lists: pos, idx = self._loc_right(value) if idx and _lists[pos][idx - 1] == value: self._delete(pos, idx - 1) def remove(self, value): """Remove `value` from sorted list; `value` must be a member.""" _len = self._len self.discard(value) if _len == self._len: raise ValueError('{0!r} not in list'.format(value)) def pop(self, index=-1): """Remove and return value at `index` in sorted list.""" pos, idx = self._fen_findkth(self._len + index if index < 0 else index) value = self._lists[pos][idx] self._delete(pos, idx) return value def bisect_left(self, value): """Return the first index to insert `value` in the sorted list.""" pos, idx = self._loc_left(value) return self._fen_query(pos) + idx def bisect_right(self, value): """Return the last index to insert `value` in the sorted list.""" pos, idx = self._loc_right(value) return self._fen_query(pos) + idx def count(self, value): """Return number of occurrences of `value` in the sorted list.""" return self.bisect_right(value) - self.bisect_left(value) def __len__(self): """Return the size of the sorted list.""" return self._len def __getitem__(self, index): """Lookup value at `index` in sorted list.""" pos, idx = self._fen_findkth(self._len + index if index < 0 else index) return self._lists[pos][idx] def __delitem__(self, index): """Remove value at `index` from sorted list.""" pos, idx = self._fen_findkth(self._len + index if index < 0 else index) self._delete(pos, idx) def __contains__(self, value): """Return true if `value` is an element of the sorted list.""" _lists = self._lists if _lists: pos, idx = self._loc_left(value) return idx < len(_lists[pos]) and _lists[pos][idx] == value return False def __iter__(self): """Return an iterator over the sorted list.""" return (value for _list in self._lists for value in _list) def __reversed__(self): """Return a reverse iterator over the sorted list.""" return (value for _list in reversed(self._lists) for value in reversed(_list)) def __repr__(self): """Return string representation of sorted list.""" return 'SortedList({0})'.format(list(self)) class SegTree: def __init__(self, n): self.N = 1 << n.bit_length() self.tree = [0] * (self.N<<1) def update(self, i, j, v): i += self.N j += self.N while i <= j: if i%2==1: self.tree[i] += v if j%2==0: self.tree[j] += v i, j = (i+1) >> 1, (j-1) >> 1 def query(self, i): v = 0 i += self.N while i > 0: v += self.tree[i] i >>= 1 return v def SieveOfEratosthenes(limit): """Returns all primes not greater than limit.""" isPrime = [True]*(limit+1) isPrime[0] = isPrime[1] = False primes = [] for i in range(2, limit+1): if not isPrime[i]:continue primes += [i] for j in range(i*i, limit+1, i): isPrime[j] = False return primes def main(): mod=1000000007 # InverseofNumber(mod) # InverseofFactorial(mod) # factorial(mod) starttime=datetime.datetime.now() if(os.path.exists('input.txt')): sys.stdin = open("input.txt","r") sys.stdout = open("output.txt","w") tc = 1 for _ in range(tc): n=ri() graph=[[] for i in range(n+1)] vis=[0]*(n+1) dist=[0]*(n+1) for i in range(n-1): a,b=ria() graph[a].append(b) graph[b].append(a) q=deque([1]) vis[1]=1 par=[0]*(n+1) while q: f=q.popleft() for child in graph[f]: if not vis[child]: par[child]=f vis[child]=1 q.append(child) dist[child]=1+dist[f] bfs=ria() flag=1 level={} pos={} level[0]=[1] pos[1]=0 for i in range(1,n): pos[bfs[i]]=i if dist[bfs[i]]<dist[bfs[i-1]]: flag=0 break if dist[bfs[i]] in level: level[dist[bfs[i]]].append(bfs[i]) else: level[dist[bfs[i]]]=[bfs[i]] if flag: for i in range(1,n): if i not in level or flag==0: break for j in range(1,len(level[i])): if pos[par[level[i][j]]]<pos[par[level[i][j-1]]]: flag=0 break if flag: ws("YES") else: ws("NO") else: ws("NO") #<--Solving Area Ends endtime=datetime.datetime.now() time=(endtime-starttime).total_seconds()*1000 if(os.path.exists('input.txt')): print("Time:",time,"ms") class FastReader(io.IOBase): newlines = 0 def __init__(self, fd, chunk_size=1024 * 8): self._fd = fd self._chunk_size = chunk_size self.buffer = io.BytesIO() def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size)) 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, size=-1): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size if size == -1 else size)) 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() class FastWriter(io.IOBase): def __init__(self, fd): self._fd = fd self.buffer = io.BytesIO() self.write = self.buffer.write def flush(self): os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class FastStdin(io.IOBase): def __init__(self, fd=0): self.buffer = FastReader(fd) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") class FastStdout(io.IOBase): def __init__(self, fd=1): self.buffer = FastWriter(fd) self.write = lambda s: self.buffer.write(s.encode("ascii")) self.flush = self.buffer.flush if __name__ == '__main__': sys.stdin = FastStdin() sys.stdout = FastStdout() main() ```
output
1
40,436
13
80,873
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The [BFS](https://en.wikipedia.org/wiki/Breadth-first_search) algorithm is defined as follows. 1. Consider an undirected graph with vertices numbered from 1 to n. Initialize q as a new [queue](http://gg.gg/queue_en) containing only vertex 1, mark the vertex 1 as used. 2. Extract a vertex v from the head of the queue q. 3. Print the index of vertex v. 4. Iterate in arbitrary order through all such vertices u that u is a neighbor of v and is not marked yet as used. Mark the vertex u as used and insert it into the tail of the queue q. 5. If the queue is not empty, continue from step 2. 6. Otherwise finish. Since the order of choosing neighbors of each vertex can vary, it turns out that there may be multiple sequences which BFS can print. In this problem you need to check whether a given sequence corresponds to some valid BFS traversal of the given tree starting from vertex 1. The [tree](http://gg.gg/tree_en) is an undirected graph, such that there is exactly one simple path between any two vertices. Input The first line contains a single integer n (1 ≀ n ≀ 2 β‹… 10^5) which denotes the number of nodes in the tree. The following n - 1 lines describe the edges of the tree. Each of them contains two integers x and y (1 ≀ x, y ≀ n) β€” the endpoints of the corresponding edge of the tree. It is guaranteed that the given graph is a tree. The last line contains n distinct integers a_1, a_2, …, a_n (1 ≀ a_i ≀ n) β€” the sequence to check. Output Print "Yes" (quotes for clarity) if the sequence corresponds to some valid BFS traversal of the given tree and "No" (quotes for clarity) otherwise. You can print each letter in any case (upper or lower). Examples Input 4 1 2 1 3 2 4 1 2 3 4 Output Yes Input 4 1 2 1 3 2 4 1 2 4 3 Output No Note Both sample tests have the same tree in them. In this tree, there are two valid BFS orderings: * 1, 2, 3, 4, * 1, 3, 2, 4. The ordering 1, 2, 4, 3 doesn't correspond to any valid BFS order. Submitted Solution: ``` import sys from collections import deque n=int(input()) visited=[False for i in range(n+2)] dp=[-1 for i in range(n+2)] l=[[] for i in range(n+2)] for i in range(n-1): a,b=map(int,input().split()) l[a].append(b) l[b].append(a) b=deque(map(int,input().split())) b.popleft() s=deque([1]) visited[1]=True while len(b)>0 and len(s)>0: aux=0 for i in l[s[0]]: if not visited[i]: visited[i]=True dp[i]=1 aux+=1 for i in range(aux): x=b.popleft() if dp[x]==1: s.append(x) dp[x]=-1 else: print("No") sys.exit() s.popleft() print("Yes") ```
instruction
0
40,437
13
80,874
Yes
output
1
40,437
13
80,875
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The [BFS](https://en.wikipedia.org/wiki/Breadth-first_search) algorithm is defined as follows. 1. Consider an undirected graph with vertices numbered from 1 to n. Initialize q as a new [queue](http://gg.gg/queue_en) containing only vertex 1, mark the vertex 1 as used. 2. Extract a vertex v from the head of the queue q. 3. Print the index of vertex v. 4. Iterate in arbitrary order through all such vertices u that u is a neighbor of v and is not marked yet as used. Mark the vertex u as used and insert it into the tail of the queue q. 5. If the queue is not empty, continue from step 2. 6. Otherwise finish. Since the order of choosing neighbors of each vertex can vary, it turns out that there may be multiple sequences which BFS can print. In this problem you need to check whether a given sequence corresponds to some valid BFS traversal of the given tree starting from vertex 1. The [tree](http://gg.gg/tree_en) is an undirected graph, such that there is exactly one simple path between any two vertices. Input The first line contains a single integer n (1 ≀ n ≀ 2 β‹… 10^5) which denotes the number of nodes in the tree. The following n - 1 lines describe the edges of the tree. Each of them contains two integers x and y (1 ≀ x, y ≀ n) β€” the endpoints of the corresponding edge of the tree. It is guaranteed that the given graph is a tree. The last line contains n distinct integers a_1, a_2, …, a_n (1 ≀ a_i ≀ n) β€” the sequence to check. Output Print "Yes" (quotes for clarity) if the sequence corresponds to some valid BFS traversal of the given tree and "No" (quotes for clarity) otherwise. You can print each letter in any case (upper or lower). Examples Input 4 1 2 1 3 2 4 1 2 3 4 Output Yes Input 4 1 2 1 3 2 4 1 2 4 3 Output No Note Both sample tests have the same tree in them. In this tree, there are two valid BFS orderings: * 1, 2, 3, 4, * 1, 3, 2, 4. The ordering 1, 2, 4, 3 doesn't correspond to any valid BFS order. Submitted Solution: ``` n=int(input()) visited=[False]*(n+1) dp=[0]*(n+1) l=[[] for i in range(n+1)] for i in range(n-1): a,b=map(int,input().split()) l[a].append(b) l[b].append(a) b=tuple(map(int,input().split())) visited[1]=True c=1 for j in range(n): aux=0 for i in l[b[j]]: if not visited[i]: visited[i]=True dp[i]=1 aux+=1 for i in range(c,c+aux): if dp[b[i]]==1: dp[b[i]]=0 else: print("No") exit() c+=aux print("Yes") ```
instruction
0
40,438
13
80,876
Yes
output
1
40,438
13
80,877
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The [BFS](https://en.wikipedia.org/wiki/Breadth-first_search) algorithm is defined as follows. 1. Consider an undirected graph with vertices numbered from 1 to n. Initialize q as a new [queue](http://gg.gg/queue_en) containing only vertex 1, mark the vertex 1 as used. 2. Extract a vertex v from the head of the queue q. 3. Print the index of vertex v. 4. Iterate in arbitrary order through all such vertices u that u is a neighbor of v and is not marked yet as used. Mark the vertex u as used and insert it into the tail of the queue q. 5. If the queue is not empty, continue from step 2. 6. Otherwise finish. Since the order of choosing neighbors of each vertex can vary, it turns out that there may be multiple sequences which BFS can print. In this problem you need to check whether a given sequence corresponds to some valid BFS traversal of the given tree starting from vertex 1. The [tree](http://gg.gg/tree_en) is an undirected graph, such that there is exactly one simple path between any two vertices. Input The first line contains a single integer n (1 ≀ n ≀ 2 β‹… 10^5) which denotes the number of nodes in the tree. The following n - 1 lines describe the edges of the tree. Each of them contains two integers x and y (1 ≀ x, y ≀ n) β€” the endpoints of the corresponding edge of the tree. It is guaranteed that the given graph is a tree. The last line contains n distinct integers a_1, a_2, …, a_n (1 ≀ a_i ≀ n) β€” the sequence to check. Output Print "Yes" (quotes for clarity) if the sequence corresponds to some valid BFS traversal of the given tree and "No" (quotes for clarity) otherwise. You can print each letter in any case (upper or lower). Examples Input 4 1 2 1 3 2 4 1 2 3 4 Output Yes Input 4 1 2 1 3 2 4 1 2 4 3 Output No Note Both sample tests have the same tree in them. In this tree, there are two valid BFS orderings: * 1, 2, 3, 4, * 1, 3, 2, 4. The ordering 1, 2, 4, 3 doesn't correspond to any valid BFS order. Submitted Solution: ``` from collections import defaultdict n=int(input()) g=defaultdict(lambda: set()) for _ in range(n-1): u, v = map(int, input().split()) g[u].add(v) g[v].add(u) check=list(map(int, input().split())) if check[0]!=1: print('No') exit() i, j = 1, 0 while i<n and j<n: if check[i] in g[check[j]]: i+=1 else: j+=1 print('Yes' if i==n else 'No') ```
instruction
0
40,439
13
80,878
Yes
output
1
40,439
13
80,879
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The [BFS](https://en.wikipedia.org/wiki/Breadth-first_search) algorithm is defined as follows. 1. Consider an undirected graph with vertices numbered from 1 to n. Initialize q as a new [queue](http://gg.gg/queue_en) containing only vertex 1, mark the vertex 1 as used. 2. Extract a vertex v from the head of the queue q. 3. Print the index of vertex v. 4. Iterate in arbitrary order through all such vertices u that u is a neighbor of v and is not marked yet as used. Mark the vertex u as used and insert it into the tail of the queue q. 5. If the queue is not empty, continue from step 2. 6. Otherwise finish. Since the order of choosing neighbors of each vertex can vary, it turns out that there may be multiple sequences which BFS can print. In this problem you need to check whether a given sequence corresponds to some valid BFS traversal of the given tree starting from vertex 1. The [tree](http://gg.gg/tree_en) is an undirected graph, such that there is exactly one simple path between any two vertices. Input The first line contains a single integer n (1 ≀ n ≀ 2 β‹… 10^5) which denotes the number of nodes in the tree. The following n - 1 lines describe the edges of the tree. Each of them contains two integers x and y (1 ≀ x, y ≀ n) β€” the endpoints of the corresponding edge of the tree. It is guaranteed that the given graph is a tree. The last line contains n distinct integers a_1, a_2, …, a_n (1 ≀ a_i ≀ n) β€” the sequence to check. Output Print "Yes" (quotes for clarity) if the sequence corresponds to some valid BFS traversal of the given tree and "No" (quotes for clarity) otherwise. You can print each letter in any case (upper or lower). Examples Input 4 1 2 1 3 2 4 1 2 3 4 Output Yes Input 4 1 2 1 3 2 4 1 2 4 3 Output No Note Both sample tests have the same tree in them. In this tree, there are two valid BFS orderings: * 1, 2, 3, 4, * 1, 3, 2, 4. The ordering 1, 2, 4, 3 doesn't correspond to any valid BFS order. Submitted Solution: ``` from sys import stdin,stdout from collections import defaultdict,Counter,deque from bisect import bisect,bisect_left import math from itertools import permutations import queue #stdin = open('input.txt','r') I = stdin.readline n = int(I()) v = defaultdict(lambda : set()) for _ in range(n-1): a,b = map(int,I().split()) v[a].add(b) v[b].add(a) arr = [int(x) for x in I().split()] if(arr[0] != 1): print("No") else: i=1 j=0 while i<n and j<n: if(arr[i] in v[arr[j]]): i+=1 else: j+=1 if(i == n): print("Yes") else: print("No") ```
instruction
0
40,440
13
80,880
Yes
output
1
40,440
13
80,881
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The [BFS](https://en.wikipedia.org/wiki/Breadth-first_search) algorithm is defined as follows. 1. Consider an undirected graph with vertices numbered from 1 to n. Initialize q as a new [queue](http://gg.gg/queue_en) containing only vertex 1, mark the vertex 1 as used. 2. Extract a vertex v from the head of the queue q. 3. Print the index of vertex v. 4. Iterate in arbitrary order through all such vertices u that u is a neighbor of v and is not marked yet as used. Mark the vertex u as used and insert it into the tail of the queue q. 5. If the queue is not empty, continue from step 2. 6. Otherwise finish. Since the order of choosing neighbors of each vertex can vary, it turns out that there may be multiple sequences which BFS can print. In this problem you need to check whether a given sequence corresponds to some valid BFS traversal of the given tree starting from vertex 1. The [tree](http://gg.gg/tree_en) is an undirected graph, such that there is exactly one simple path between any two vertices. Input The first line contains a single integer n (1 ≀ n ≀ 2 β‹… 10^5) which denotes the number of nodes in the tree. The following n - 1 lines describe the edges of the tree. Each of them contains two integers x and y (1 ≀ x, y ≀ n) β€” the endpoints of the corresponding edge of the tree. It is guaranteed that the given graph is a tree. The last line contains n distinct integers a_1, a_2, …, a_n (1 ≀ a_i ≀ n) β€” the sequence to check. Output Print "Yes" (quotes for clarity) if the sequence corresponds to some valid BFS traversal of the given tree and "No" (quotes for clarity) otherwise. You can print each letter in any case (upper or lower). Examples Input 4 1 2 1 3 2 4 1 2 3 4 Output Yes Input 4 1 2 1 3 2 4 1 2 4 3 Output No Note Both sample tests have the same tree in them. In this tree, there are two valid BFS orderings: * 1, 2, 3, 4, * 1, 3, 2, 4. The ordering 1, 2, 4, 3 doesn't correspond to any valid BFS order. Submitted Solution: ``` from collections import defaultdict graph = defaultdict(list) n= int(input()) visited = [False]*n pred = {} queue =[] for _ in range(n-1): a,b = list(map(int,input().split())) graph[a].append(b) graph[b].append(a) l = list(map(int,input().split())) visited[0] = True pred[1] = None queue.append(1) while len(queue) != 0 : front = queue.pop(0) for i in graph[front]: if not visited[i-1]: queue.append(i) visited[i-1] = True pred[i]=front prev = 0 flag = 0 for i in range(1,n): if pred[l[i]] >= prev: prev = pred[l[i]] else: flag = 1 break if flag == 1: print('No') else: print('Yes') ```
instruction
0
40,441
13
80,882
No
output
1
40,441
13
80,883
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The [BFS](https://en.wikipedia.org/wiki/Breadth-first_search) algorithm is defined as follows. 1. Consider an undirected graph with vertices numbered from 1 to n. Initialize q as a new [queue](http://gg.gg/queue_en) containing only vertex 1, mark the vertex 1 as used. 2. Extract a vertex v from the head of the queue q. 3. Print the index of vertex v. 4. Iterate in arbitrary order through all such vertices u that u is a neighbor of v and is not marked yet as used. Mark the vertex u as used and insert it into the tail of the queue q. 5. If the queue is not empty, continue from step 2. 6. Otherwise finish. Since the order of choosing neighbors of each vertex can vary, it turns out that there may be multiple sequences which BFS can print. In this problem you need to check whether a given sequence corresponds to some valid BFS traversal of the given tree starting from vertex 1. The [tree](http://gg.gg/tree_en) is an undirected graph, such that there is exactly one simple path between any two vertices. Input The first line contains a single integer n (1 ≀ n ≀ 2 β‹… 10^5) which denotes the number of nodes in the tree. The following n - 1 lines describe the edges of the tree. Each of them contains two integers x and y (1 ≀ x, y ≀ n) β€” the endpoints of the corresponding edge of the tree. It is guaranteed that the given graph is a tree. The last line contains n distinct integers a_1, a_2, …, a_n (1 ≀ a_i ≀ n) β€” the sequence to check. Output Print "Yes" (quotes for clarity) if the sequence corresponds to some valid BFS traversal of the given tree and "No" (quotes for clarity) otherwise. You can print each letter in any case (upper or lower). Examples Input 4 1 2 1 3 2 4 1 2 3 4 Output Yes Input 4 1 2 1 3 2 4 1 2 4 3 Output No Note Both sample tests have the same tree in them. In this tree, there are two valid BFS orderings: * 1, 2, 3, 4, * 1, 3, 2, 4. The ordering 1, 2, 4, 3 doesn't correspond to any valid BFS order. Submitted Solution: ``` # python rough_work.py < in > out && cat out && diff -qs out check from queue import Queue n = int(input()) adjList = [[] for _ in range(n+1)] # print(adjList) for _ in range(n-1): from_, to = (int(var) for var in input().split()) # print(from_, to) adjList[from_].append(to) bfs = [int(var) for var in input().split()] if bfs[0] == 1: flag = True q = Queue() q.put(1) currPointer = 1 while not q.empty(): currNode = q.get() if len(adjList[currNode]) == 0: pass elif bfs[currPointer:currPointer+len(adjList[currNode])] == adjList[currNode]: for node in adjList[currNode]: q.put(node) currPointer += 1 elif bfs[currPointer:currPointer+len(adjList[currNode])] == list(reversed(adjList[currNode])): for node in reversed(adjList[currNode]): q.put(node) currPointer += 1 else: flag = False break print("Yes" if flag else "No") else: print('No') ```
instruction
0
40,442
13
80,884
No
output
1
40,442
13
80,885
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The [BFS](https://en.wikipedia.org/wiki/Breadth-first_search) algorithm is defined as follows. 1. Consider an undirected graph with vertices numbered from 1 to n. Initialize q as a new [queue](http://gg.gg/queue_en) containing only vertex 1, mark the vertex 1 as used. 2. Extract a vertex v from the head of the queue q. 3. Print the index of vertex v. 4. Iterate in arbitrary order through all such vertices u that u is a neighbor of v and is not marked yet as used. Mark the vertex u as used and insert it into the tail of the queue q. 5. If the queue is not empty, continue from step 2. 6. Otherwise finish. Since the order of choosing neighbors of each vertex can vary, it turns out that there may be multiple sequences which BFS can print. In this problem you need to check whether a given sequence corresponds to some valid BFS traversal of the given tree starting from vertex 1. The [tree](http://gg.gg/tree_en) is an undirected graph, such that there is exactly one simple path between any two vertices. Input The first line contains a single integer n (1 ≀ n ≀ 2 β‹… 10^5) which denotes the number of nodes in the tree. The following n - 1 lines describe the edges of the tree. Each of them contains two integers x and y (1 ≀ x, y ≀ n) β€” the endpoints of the corresponding edge of the tree. It is guaranteed that the given graph is a tree. The last line contains n distinct integers a_1, a_2, …, a_n (1 ≀ a_i ≀ n) β€” the sequence to check. Output Print "Yes" (quotes for clarity) if the sequence corresponds to some valid BFS traversal of the given tree and "No" (quotes for clarity) otherwise. You can print each letter in any case (upper or lower). Examples Input 4 1 2 1 3 2 4 1 2 3 4 Output Yes Input 4 1 2 1 3 2 4 1 2 4 3 Output No Note Both sample tests have the same tree in them. In this tree, there are two valid BFS orderings: * 1, 2, 3, 4, * 1, 3, 2, 4. The ordering 1, 2, 4, 3 doesn't correspond to any valid BFS order. Submitted Solution: ``` from collections import deque n=int(input()) g=[[] for _ in range(n)] for _ in range(n-1): a,b=map(int,input().split()) g[a-1].append(b-1) g[b-1].append(a-1) a=list(map(int,input().split())) v=[-1]*n v[0]=1 q=deque(a,n) r=[a[0]] while q: x=q.popleft()-1 for j in g[x]: if v[j]==-1: v[j]=1 r.append(j+1) if r!=a:print('No') else: print('Yes') ```
instruction
0
40,443
13
80,886
No
output
1
40,443
13
80,887
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The [BFS](https://en.wikipedia.org/wiki/Breadth-first_search) algorithm is defined as follows. 1. Consider an undirected graph with vertices numbered from 1 to n. Initialize q as a new [queue](http://gg.gg/queue_en) containing only vertex 1, mark the vertex 1 as used. 2. Extract a vertex v from the head of the queue q. 3. Print the index of vertex v. 4. Iterate in arbitrary order through all such vertices u that u is a neighbor of v and is not marked yet as used. Mark the vertex u as used and insert it into the tail of the queue q. 5. If the queue is not empty, continue from step 2. 6. Otherwise finish. Since the order of choosing neighbors of each vertex can vary, it turns out that there may be multiple sequences which BFS can print. In this problem you need to check whether a given sequence corresponds to some valid BFS traversal of the given tree starting from vertex 1. The [tree](http://gg.gg/tree_en) is an undirected graph, such that there is exactly one simple path between any two vertices. Input The first line contains a single integer n (1 ≀ n ≀ 2 β‹… 10^5) which denotes the number of nodes in the tree. The following n - 1 lines describe the edges of the tree. Each of them contains two integers x and y (1 ≀ x, y ≀ n) β€” the endpoints of the corresponding edge of the tree. It is guaranteed that the given graph is a tree. The last line contains n distinct integers a_1, a_2, …, a_n (1 ≀ a_i ≀ n) β€” the sequence to check. Output Print "Yes" (quotes for clarity) if the sequence corresponds to some valid BFS traversal of the given tree and "No" (quotes for clarity) otherwise. You can print each letter in any case (upper or lower). Examples Input 4 1 2 1 3 2 4 1 2 3 4 Output Yes Input 4 1 2 1 3 2 4 1 2 4 3 Output No Note Both sample tests have the same tree in them. In this tree, there are two valid BFS orderings: * 1, 2, 3, 4, * 1, 3, 2, 4. The ordering 1, 2, 4, 3 doesn't correspond to any valid BFS order. Submitted Solution: ``` class Node: def __init__(self, value, child_list): self.value = value self.child_list = child_list def append_child(self, value): if self.child_list: self.child_list.append(value) else: self.child_list = [value] # node_list: access node as its number def is_valid_DFS(node_map, visit_list): if len(node_map) == 0: return True queue = [set([visit_list[0]])] visited = set() visit_i = 0 while len(queue) != 0: cur_set = queue[0] del queue[0] cur_compare = visit_list[visit_i: visit_i + len(cur_set)] if cur_set != set(cur_compare): return False for n in cur_compare: if n in visited: return False else: visited.add(n) visit_i += len(cur_compare) for n in cur_compare: child_list = node_map[n].child_list if child_list: queue.append(set(child_list)) return True if __name__ == '__main__': import sys node_m = {} size = int(sys.stdin.readline()) for _ in range(size - 1): p, c = map(int, sys.stdin.readline().split()) if node_m.get(p): node_m[p].append_child(c) else: node_m[p] = Node(p, [c]) if not node_m.get(c): node_m[c] = Node(c, None) v_list = list(map(int, sys.stdin.readline().split())) if is_valid_DFS(node_m, v_list): print('Yes') else: print('No') ```
instruction
0
40,444
13
80,888
No
output
1
40,444
13
80,889
Provide tags and a correct Python 3 solution for this coding contest problem. You are given two integers n and d. You need to construct a rooted binary tree consisting of n vertices with a root at the vertex 1 and the sum of depths of all vertices equals to d. A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a vertex v is the last different from v vertex on the path from the root to the vertex v. The depth of the vertex v is the length of the path from the root to the vertex v. Children of vertex v are all vertices for which v is the parent. The binary tree is such a tree that no vertex has more than 2 children. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≀ t ≀ 1000) β€” the number of test cases. The only line of each test case contains two integers n and d (2 ≀ n, d ≀ 5000) β€” the number of vertices in the tree and the required sum of depths of all vertices. It is guaranteed that the sum of n and the sum of d both does not exceed 5000 (βˆ‘ n ≀ 5000, βˆ‘ d ≀ 5000). Output For each test case, print the answer. If it is impossible to construct such a tree, print "NO" (without quotes) in the first line. Otherwise, print "{YES}" in the first line. Then print n-1 integers p_2, p_3, ..., p_n in the second line, where p_i is the parent of the vertex i. Note that the sequence of parents you print should describe some binary tree. Example Input 3 5 7 10 19 10 18 Output YES 1 2 1 3 YES 1 2 3 3 9 9 2 1 6 NO Note Pictures corresponding to the first and the second test cases of the example: <image> <image>
instruction
0
40,543
13
81,086
Tags: brute force, constructive algorithms, trees Correct Solution: ``` # 3/2/2020, 8:23 PM # edited to just edit the parent array import math import sys import operator # note that we will only increase the depth of a node, never decrease def raise_d(parent): # find the deepest depth that has more than one vertex just_parent = [i for i, j in parent] for deep in range(n - 1, -1, -1): if depth_track[deep] >= 2: break deep_nodes = [] c = 0 for p, depth in parent[::-1]: if depth == deep: deep_nodes.append(n - c) if len(deep_nodes) == 2: break c += 1 # deep_nodes contains vertices at depth = deep for NC in deep_nodes: if just_parent.count(NC) == 0: C ,= [x for x in deep_nodes if x != NC] break # now we have NC with at most one child and C the other node # we just have to move NC to be a child of C parent[NC] = C, deep + 1 depth_track[deep + 1] += 1 depth_track[deep] -= 1 return parent T = int(input()) for _ in range(T): # 2 cases: one where we use as little vertices and # another where we fill us levels are much as we can n, d = map(int, input().split()) # upper bound ub = n*(n - 1)//2 # calculating the lower bound count = n depth = 0 lb = 0 while count > 0: depth_count = 2**depth fill = min(count, depth_count) count -= fill lb += fill*depth depth += 1 # testing d against bounds if not (lb <= d <= ub): print ('NO') continue # create an array to keep track of how many nodes are at each depth depth_track = [0]*(n) # create the parent array for lower bound parent = [(-1, -1) for i in range(n + 1)] for i in range(1, n + 1): if i % 2 == 1: p = (i - 1)//2 depth = len(bin(i)) - 3 parent[i] = (p, depth) depth_track[depth] += 1 else: p = i//2 depth = len(bin(i)) - 3 parent[i] = (p, depth) depth_track[depth] += 1 for i in range(d - lb): parent = raise_d(parent) print ('YES') # making an array so that vertex v at index v - 1 has its parent node there parent = [p for p, depth in parent if depth != 0 and depth != -1] print (*parent) ```
output
1
40,543
13
81,087
Provide tags and a correct Python 3 solution for this coding contest problem. You are given two integers n and d. You need to construct a rooted binary tree consisting of n vertices with a root at the vertex 1 and the sum of depths of all vertices equals to d. A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a vertex v is the last different from v vertex on the path from the root to the vertex v. The depth of the vertex v is the length of the path from the root to the vertex v. Children of vertex v are all vertices for which v is the parent. The binary tree is such a tree that no vertex has more than 2 children. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≀ t ≀ 1000) β€” the number of test cases. The only line of each test case contains two integers n and d (2 ≀ n, d ≀ 5000) β€” the number of vertices in the tree and the required sum of depths of all vertices. It is guaranteed that the sum of n and the sum of d both does not exceed 5000 (βˆ‘ n ≀ 5000, βˆ‘ d ≀ 5000). Output For each test case, print the answer. If it is impossible to construct such a tree, print "NO" (without quotes) in the first line. Otherwise, print "{YES}" in the first line. Then print n-1 integers p_2, p_3, ..., p_n in the second line, where p_i is the parent of the vertex i. Note that the sequence of parents you print should describe some binary tree. Example Input 3 5 7 10 19 10 18 Output YES 1 2 1 3 YES 1 2 3 3 9 9 2 1 6 NO Note Pictures corresponding to the first and the second test cases of the example: <image> <image>
instruction
0
40,544
13
81,088
Tags: brute force, constructive algorithms, trees Correct Solution: ``` t = int(input()) for T in range(t): n, d = map(int, input().strip().split()) u = (n-1) * n // 2 if d > u: print("NO"); continue l = t = 0 for i in range(1, 1+n): l += t if not i & i+1: t += 1 if d < l: print("NO"); continue p = [1] * n l = [1 << i for i in range(n)] o = n-1 while u > d: m = o while u > d and m and p[m-1] < l[m-1]: m -= 1; u -= 1; p[o] -= 1; p[m] += 1; o -= 1 r = [0] * n c = [1, 1] t = [] v = 1 for i in range(1, n): if not p[i]: break for j in range(p[i]): r[v] = c.pop() v += 1 t.append(v) t.append(v) c = t t = [] print("YES") print(*(r[i] for i in range(1, n))) ```
output
1
40,544
13
81,089
Provide tags and a correct Python 3 solution for this coding contest problem. You are given two integers n and d. You need to construct a rooted binary tree consisting of n vertices with a root at the vertex 1 and the sum of depths of all vertices equals to d. A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a vertex v is the last different from v vertex on the path from the root to the vertex v. The depth of the vertex v is the length of the path from the root to the vertex v. Children of vertex v are all vertices for which v is the parent. The binary tree is such a tree that no vertex has more than 2 children. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≀ t ≀ 1000) β€” the number of test cases. The only line of each test case contains two integers n and d (2 ≀ n, d ≀ 5000) β€” the number of vertices in the tree and the required sum of depths of all vertices. It is guaranteed that the sum of n and the sum of d both does not exceed 5000 (βˆ‘ n ≀ 5000, βˆ‘ d ≀ 5000). Output For each test case, print the answer. If it is impossible to construct such a tree, print "NO" (without quotes) in the first line. Otherwise, print "{YES}" in the first line. Then print n-1 integers p_2, p_3, ..., p_n in the second line, where p_i is the parent of the vertex i. Note that the sequence of parents you print should describe some binary tree. Example Input 3 5 7 10 19 10 18 Output YES 1 2 1 3 YES 1 2 3 3 9 9 2 1 6 NO Note Pictures corresponding to the first and the second test cases of the example: <image> <image>
instruction
0
40,545
13
81,090
Tags: brute force, constructive algorithms, trees Correct Solution: ``` for tests in range(int(input())): n, d = map(int,input().split()) upper_bound, lower_bound, lv = n * (n - 1) // 2, 0, 0 for i in range(1, n + 1): if not(i & (i - 1)): lv += 1 lower_bound += lv - 1 if not(d in range(lower_bound, upper_bound + 1)): print("NO") else: bad = [False] * n depth = list(range(n)) count_child = [1] * n count_child[n - 1] = 0 current_depth = upper_bound parent = list(range(-1,n-1)) while current_depth > d: v = -1 for i in range(n): if not(bad[i]) and count_child[i] == 0 and (v == -1 or depth[i] < depth[v]): v = i if(v == -1): break p = -1 for i in range(n): if count_child[i] < 2 and depth[i] == depth[v] - 2 and (p == -1 or depth[i] > depth[p]): p = i if p == -1: bad[v] = True continue count_child[parent[v]] -= 1 depth[v] -= 1 count_child[p] += 1 parent[v] = p current_depth -= 1 if current_depth == d: print("YES") for i in range(1,n): print(parent[i] + 1, end=' ') print() else: print("NO") ```
output
1
40,545
13
81,091
Provide tags and a correct Python 3 solution for this coding contest problem. You are given two integers n and d. You need to construct a rooted binary tree consisting of n vertices with a root at the vertex 1 and the sum of depths of all vertices equals to d. A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a vertex v is the last different from v vertex on the path from the root to the vertex v. The depth of the vertex v is the length of the path from the root to the vertex v. Children of vertex v are all vertices for which v is the parent. The binary tree is such a tree that no vertex has more than 2 children. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≀ t ≀ 1000) β€” the number of test cases. The only line of each test case contains two integers n and d (2 ≀ n, d ≀ 5000) β€” the number of vertices in the tree and the required sum of depths of all vertices. It is guaranteed that the sum of n and the sum of d both does not exceed 5000 (βˆ‘ n ≀ 5000, βˆ‘ d ≀ 5000). Output For each test case, print the answer. If it is impossible to construct such a tree, print "NO" (without quotes) in the first line. Otherwise, print "{YES}" in the first line. Then print n-1 integers p_2, p_3, ..., p_n in the second line, where p_i is the parent of the vertex i. Note that the sequence of parents you print should describe some binary tree. Example Input 3 5 7 10 19 10 18 Output YES 1 2 1 3 YES 1 2 3 3 9 9 2 1 6 NO Note Pictures corresponding to the first and the second test cases of the example: <image> <image>
instruction
0
40,546
13
81,092
Tags: brute force, constructive algorithms, trees Correct Solution: ``` from math import ceil,floor,log t=int(input()) for i2 in range(t): n,d=map(int,input().split()) p,dad=0,[0]*(n+1) c=(n*(n-1))//2 for i in range(1,n+1): p+=floor(log(i,2)) if p>d or c<d: print("NO") continue now=1 dad=[0]*(n+1) vec=[[]for i in range(n+1)] for i in range(1,n+1): vec[i-1].append(i) for i in range(n,0,-1): if c-d<=i-1-now: vec[now].append(i) dad[i]=vec[i-2-(c-d)][(len(vec[i-(c-d)-1])+1)//2-1] break else: vec[now].append(i) dad[i]=vec[now-1][(len(vec[now])+1)//2-1] c-=i-1-now if len(vec[now])>=2**now: now+=1 print("YES") for i in range(2,n+1): if dad[i]==0: print(i-1,end=" ") else: print(dad[i],end=" ") print("") ```
output
1
40,546
13
81,093
Provide tags and a correct Python 3 solution for this coding contest problem. You are given two integers n and d. You need to construct a rooted binary tree consisting of n vertices with a root at the vertex 1 and the sum of depths of all vertices equals to d. A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a vertex v is the last different from v vertex on the path from the root to the vertex v. The depth of the vertex v is the length of the path from the root to the vertex v. Children of vertex v are all vertices for which v is the parent. The binary tree is such a tree that no vertex has more than 2 children. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≀ t ≀ 1000) β€” the number of test cases. The only line of each test case contains two integers n and d (2 ≀ n, d ≀ 5000) β€” the number of vertices in the tree and the required sum of depths of all vertices. It is guaranteed that the sum of n and the sum of d both does not exceed 5000 (βˆ‘ n ≀ 5000, βˆ‘ d ≀ 5000). Output For each test case, print the answer. If it is impossible to construct such a tree, print "NO" (without quotes) in the first line. Otherwise, print "{YES}" in the first line. Then print n-1 integers p_2, p_3, ..., p_n in the second line, where p_i is the parent of the vertex i. Note that the sequence of parents you print should describe some binary tree. Example Input 3 5 7 10 19 10 18 Output YES 1 2 1 3 YES 1 2 3 3 9 9 2 1 6 NO Note Pictures corresponding to the first and the second test cases of the example: <image> <image>
instruction
0
40,547
13
81,094
Tags: brute force, constructive algorithms, trees Correct Solution: ``` t=int(input()) import math as m def print_tree(l): t=[{'p':None, 'c':[]} for i in range(sum(l))] l2={i:[] for i in range(len(l))} j=0 for i in range(sum(l)): l2[j].append(i+1) if len(l2[j])==l[j]: j+=1 for i in range(1,len(l)): p=0 for n in l2[i]: pi=l2[i-1][p] t[n-1]['p']=pi t[pi-1]['c'].append(n) if len(t[pi-1]['c'])==2: p+=1 for i in range(1, len(t)): print(t[i]['p'], end=' ') print() for _ in range(t): n, d = map(int, input().split()) k=m.floor(m.log2(n)) maxd=n*(n-1)//2 mind=k*2**(k+1)-2**(k+1)+2+k*(n-2**(k+1)+1) if (d<mind) or (d>maxd): print("NO") continue l=[1 for i in range(n)] s=maxd lowest=1 highest=n-1 while (s>d): diff=s-d if (diff>highest-lowest): l[highest]-=1 l[lowest]+=1 s-=(highest-lowest) highest-=1 if l[lowest-1]*2==l[lowest]: lowest+=1 else: level=highest-diff l[level]+=1 l[highest]-=1 s-=diff print("YES") print_tree(l) ```
output
1
40,547
13
81,095
Provide tags and a correct Python 3 solution for this coding contest problem. You are given two integers n and d. You need to construct a rooted binary tree consisting of n vertices with a root at the vertex 1 and the sum of depths of all vertices equals to d. A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a vertex v is the last different from v vertex on the path from the root to the vertex v. The depth of the vertex v is the length of the path from the root to the vertex v. Children of vertex v are all vertices for which v is the parent. The binary tree is such a tree that no vertex has more than 2 children. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≀ t ≀ 1000) β€” the number of test cases. The only line of each test case contains two integers n and d (2 ≀ n, d ≀ 5000) β€” the number of vertices in the tree and the required sum of depths of all vertices. It is guaranteed that the sum of n and the sum of d both does not exceed 5000 (βˆ‘ n ≀ 5000, βˆ‘ d ≀ 5000). Output For each test case, print the answer. If it is impossible to construct such a tree, print "NO" (without quotes) in the first line. Otherwise, print "{YES}" in the first line. Then print n-1 integers p_2, p_3, ..., p_n in the second line, where p_i is the parent of the vertex i. Note that the sequence of parents you print should describe some binary tree. Example Input 3 5 7 10 19 10 18 Output YES 1 2 1 3 YES 1 2 3 3 9 9 2 1 6 NO Note Pictures corresponding to the first and the second test cases of the example: <image> <image>
instruction
0
40,548
13
81,096
Tags: brute force, constructive algorithms, trees Correct Solution: ``` for tests in range(int(input())): n, d = map(int,input().split()) upper_bound, lower_bound, lv = n * (n - 1) // 2, 0, 0 for i in range(1, n + 1): if not(i & (i - 1)): lv += 1 lower_bound += lv - 1 if not(d in range(lower_bound, upper_bound + 1)): print("NO") else: bad = [False] * n depth = list(range(n)) count_child = [1] * n count_child[n - 1] = 0 current_depth = upper_bound parent = list(range(-1,n-1)) while current_depth > d: v, p = -1, -1 for i in range(n): if not(bad[i]) and count_child[i] == 0 and (v == -1 or depth[i] < depth[v]): v = i for i in range(n): if count_child[i] < 2 and depth[i] == depth[v] - 2 and (p == -1 or depth[i] > depth[p]): p = i if p == -1: bad[v] = True continue count_child[parent[v]] -= 1 depth[v] -= 1 count_child[p] += 1 parent[v] = p current_depth -= 1 print("YES") print(*((parent[i] + 1) for i in range(1,n))) ```
output
1
40,548
13
81,097
Provide tags and a correct Python 3 solution for this coding contest problem. You are given two integers n and d. You need to construct a rooted binary tree consisting of n vertices with a root at the vertex 1 and the sum of depths of all vertices equals to d. A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a vertex v is the last different from v vertex on the path from the root to the vertex v. The depth of the vertex v is the length of the path from the root to the vertex v. Children of vertex v are all vertices for which v is the parent. The binary tree is such a tree that no vertex has more than 2 children. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≀ t ≀ 1000) β€” the number of test cases. The only line of each test case contains two integers n and d (2 ≀ n, d ≀ 5000) β€” the number of vertices in the tree and the required sum of depths of all vertices. It is guaranteed that the sum of n and the sum of d both does not exceed 5000 (βˆ‘ n ≀ 5000, βˆ‘ d ≀ 5000). Output For each test case, print the answer. If it is impossible to construct such a tree, print "NO" (without quotes) in the first line. Otherwise, print "{YES}" in the first line. Then print n-1 integers p_2, p_3, ..., p_n in the second line, where p_i is the parent of the vertex i. Note that the sequence of parents you print should describe some binary tree. Example Input 3 5 7 10 19 10 18 Output YES 1 2 1 3 YES 1 2 3 3 9 9 2 1 6 NO Note Pictures corresponding to the first and the second test cases of the example: <image> <image>
instruction
0
40,549
13
81,098
Tags: brute force, constructive algorithms, trees Correct Solution: ``` #Pye from os import path from sys import stdin, stdout if path.exists('inp.txt'): stdin = open("inp.txt", "r") maxn = 5005 q = int(stdin.readline()) for _ in range(q): n, d = map(int, stdin.readline().split()) a = [0 for i in range(maxn)] b = [0 for i in range(maxn)] use = [0 for i in range(maxn)] ans = [0 for i in range(maxn)] row = [[] for i in range(maxn)] left = int((n * (n-1)) / 2) - d pos = n for i in range(2, n+1): b[i] = 1; a[i] = i-1 while left and pos >= 2: for i in range(1, pos+1): if b[i] > 0 and left >= pos - i: left -= pos - i; a[pos] = i - 1; b[i + 1] += 2; b[i] -= 1; break pos -= 1 if left: print("NO") else: print("YES") a = sorted(a[0:(n+1)]) row[0].append(1) for i in range(2, n+1): for v in row[a[i]-1]: if use[v] < 2: use[v] += 1; ans[i] = v; row[a[i]].append(i); break print(*ans[2:(n+1)]) ```
output
1
40,549
13
81,099
Provide tags and a correct Python 3 solution for this coding contest problem. You are given two integers n and d. You need to construct a rooted binary tree consisting of n vertices with a root at the vertex 1 and the sum of depths of all vertices equals to d. A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a vertex v is the last different from v vertex on the path from the root to the vertex v. The depth of the vertex v is the length of the path from the root to the vertex v. Children of vertex v are all vertices for which v is the parent. The binary tree is such a tree that no vertex has more than 2 children. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≀ t ≀ 1000) β€” the number of test cases. The only line of each test case contains two integers n and d (2 ≀ n, d ≀ 5000) β€” the number of vertices in the tree and the required sum of depths of all vertices. It is guaranteed that the sum of n and the sum of d both does not exceed 5000 (βˆ‘ n ≀ 5000, βˆ‘ d ≀ 5000). Output For each test case, print the answer. If it is impossible to construct such a tree, print "NO" (without quotes) in the first line. Otherwise, print "{YES}" in the first line. Then print n-1 integers p_2, p_3, ..., p_n in the second line, where p_i is the parent of the vertex i. Note that the sequence of parents you print should describe some binary tree. Example Input 3 5 7 10 19 10 18 Output YES 1 2 1 3 YES 1 2 3 3 9 9 2 1 6 NO Note Pictures corresponding to the first and the second test cases of the example: <image> <image>
instruction
0
40,550
13
81,100
Tags: brute force, constructive algorithms, trees Correct Solution: ``` t=int(input()) pows=[2**i for i in range(21)] for _ in range(t): n,d=map(int,input().split()) mins=0 for k in range(20): if pows[k+1]<=n: mins+=k*pows[k] else: mins+=k*(n-(pows[k]-1)) break maxs=n*(n-1)//2 if d<mins or d>maxs: print('NO') else: print('YES') ans=[i for i in range(n)] cnt=1 base=1 for i in range(n-1,-1,-1): if maxs-(ans[i]-base)>d: maxs-=ans[i]-base ans[i]=base cnt+=1 if cnt==pows[base]: base+=1 cnt=1 else: ans[i]-=(maxs-d) break ans=sorted(ans) arr=[[] for _ in range(n+1)] for i in range(n): arr[ans[i]].append(i+1) ret=[] for i in range(1,n+1): pos=0 cnt=0 for j in range(len(arr[i])): ret.append(arr[i-1][pos]) cnt+=1 if cnt==2: pos+=1 cnt=0 print(*ret) ```
output
1
40,550
13
81,101
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given two integers n and d. You need to construct a rooted binary tree consisting of n vertices with a root at the vertex 1 and the sum of depths of all vertices equals to d. A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a vertex v is the last different from v vertex on the path from the root to the vertex v. The depth of the vertex v is the length of the path from the root to the vertex v. Children of vertex v are all vertices for which v is the parent. The binary tree is such a tree that no vertex has more than 2 children. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≀ t ≀ 1000) β€” the number of test cases. The only line of each test case contains two integers n and d (2 ≀ n, d ≀ 5000) β€” the number of vertices in the tree and the required sum of depths of all vertices. It is guaranteed that the sum of n and the sum of d both does not exceed 5000 (βˆ‘ n ≀ 5000, βˆ‘ d ≀ 5000). Output For each test case, print the answer. If it is impossible to construct such a tree, print "NO" (without quotes) in the first line. Otherwise, print "{YES}" in the first line. Then print n-1 integers p_2, p_3, ..., p_n in the second line, where p_i is the parent of the vertex i. Note that the sequence of parents you print should describe some binary tree. Example Input 3 5 7 10 19 10 18 Output YES 1 2 1 3 YES 1 2 3 3 9 9 2 1 6 NO Note Pictures corresponding to the first and the second test cases of the example: <image> <image> Submitted Solution: ``` t = int(input()) for _ in range(t): n,d = map(int,input().split()) dsum = n*(n-1)//2 if d>dsum: print("NO") continue tree = [[i] for i in range(n)] lmin = 1 while dsum > d: l = len(tree)-1 while dsum > d and l>lmin: l -= 1 dsum -= 1 if l == len(tree)-1: break node = tree[-1][-1] tree[-1].pop() if not tree[-1]: tree.pop() tree[l].append(node) if len(tree[l])==2**l: lmin += 1 if dsum > d: print("NO") continue print("YES") parent = [0]*(n-1) for j in range(1,len(tree)): layer = tree[j] for i in range(len(layer)): node = layer[i] parent[node-1] = tree[j-1][i//2] + 1 print(*parent) ```
instruction
0
40,551
13
81,102
Yes
output
1
40,551
13
81,103
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given two integers n and d. You need to construct a rooted binary tree consisting of n vertices with a root at the vertex 1 and the sum of depths of all vertices equals to d. A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a vertex v is the last different from v vertex on the path from the root to the vertex v. The depth of the vertex v is the length of the path from the root to the vertex v. Children of vertex v are all vertices for which v is the parent. The binary tree is such a tree that no vertex has more than 2 children. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≀ t ≀ 1000) β€” the number of test cases. The only line of each test case contains two integers n and d (2 ≀ n, d ≀ 5000) β€” the number of vertices in the tree and the required sum of depths of all vertices. It is guaranteed that the sum of n and the sum of d both does not exceed 5000 (βˆ‘ n ≀ 5000, βˆ‘ d ≀ 5000). Output For each test case, print the answer. If it is impossible to construct such a tree, print "NO" (without quotes) in the first line. Otherwise, print "{YES}" in the first line. Then print n-1 integers p_2, p_3, ..., p_n in the second line, where p_i is the parent of the vertex i. Note that the sequence of parents you print should describe some binary tree. Example Input 3 5 7 10 19 10 18 Output YES 1 2 1 3 YES 1 2 3 3 9 9 2 1 6 NO Note Pictures corresponding to the first and the second test cases of the example: <image> <image> Submitted Solution: ``` for _ in range(int(input())): n, d = map(int, input().split()) ld, rd = 0, n * (n - 1) // 2 tn = n cd = 0 mvl = 1 while tn: vl = min(tn, mvl) ld += cd * vl cd += 1 tn -= vl mvl *= 2 if not (ld <= d <= rd): print('NO') continue parent = [i-1 for i in range(n)] bad = [False] * n deep = [i for i in range(n)] child = [1] * n child[-1] = 0 cur = rd while cur > d: v = None for i in range(n): if not bad[i] and not child[i] and (v is None or deep[i] < deep[v]): v = i p = None for i in range(n): if child[i] < 2 and deep[i] < deep[v] - 1 and (p is None or deep[i] > deep[p]): p = i if p is None: bad[v] = True else: child[parent[v]] -= 1 deep[v] -= 1 child[p] += 1 parent[v] = p cur -= 1 print('YES') print(*map(lambda x: x + 1, parent[1:])) ```
instruction
0
40,552
13
81,104
Yes
output
1
40,552
13
81,105
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given two integers n and d. You need to construct a rooted binary tree consisting of n vertices with a root at the vertex 1 and the sum of depths of all vertices equals to d. A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a vertex v is the last different from v vertex on the path from the root to the vertex v. The depth of the vertex v is the length of the path from the root to the vertex v. Children of vertex v are all vertices for which v is the parent. The binary tree is such a tree that no vertex has more than 2 children. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≀ t ≀ 1000) β€” the number of test cases. The only line of each test case contains two integers n and d (2 ≀ n, d ≀ 5000) β€” the number of vertices in the tree and the required sum of depths of all vertices. It is guaranteed that the sum of n and the sum of d both does not exceed 5000 (βˆ‘ n ≀ 5000, βˆ‘ d ≀ 5000). Output For each test case, print the answer. If it is impossible to construct such a tree, print "NO" (without quotes) in the first line. Otherwise, print "{YES}" in the first line. Then print n-1 integers p_2, p_3, ..., p_n in the second line, where p_i is the parent of the vertex i. Note that the sequence of parents you print should describe some binary tree. Example Input 3 5 7 10 19 10 18 Output YES 1 2 1 3 YES 1 2 3 3 9 9 2 1 6 NO Note Pictures corresponding to the first and the second test cases of the example: <image> <image> Submitted Solution: ``` import sys input = sys.stdin.readline t=int(input()) for tests in range(t): n,d=map(int,input().split()) MIN=sum([i.bit_length()-1 for i in range(1,n+1)]) MAX=(n-1)*n//2 if MIN<=d<=MAX: print("YES") else: print("NO") continue TREE=[i//2 for i in range(n+1)] STEM=[1<<i for i in range(n.bit_length())] SETSTEM=set(STEM) rest=d-MIN #print(TREE,STEM,rest) for x in range(n,-1,-1): if x in SETSTEM: continue if rest==0: break now_height=x.bit_length()-1 max_height=len(STEM) #print(x,now_height,max_height) if rest>max_height-now_height: rest-=max_height-now_height TREE[x]=STEM[-1] STEM.append(x) else: TREE[x]=STEM[now_height+rest-1] break print(*TREE[2:]) ```
instruction
0
40,553
13
81,106
Yes
output
1
40,553
13
81,107
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given two integers n and d. You need to construct a rooted binary tree consisting of n vertices with a root at the vertex 1 and the sum of depths of all vertices equals to d. A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a vertex v is the last different from v vertex on the path from the root to the vertex v. The depth of the vertex v is the length of the path from the root to the vertex v. Children of vertex v are all vertices for which v is the parent. The binary tree is such a tree that no vertex has more than 2 children. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≀ t ≀ 1000) β€” the number of test cases. The only line of each test case contains two integers n and d (2 ≀ n, d ≀ 5000) β€” the number of vertices in the tree and the required sum of depths of all vertices. It is guaranteed that the sum of n and the sum of d both does not exceed 5000 (βˆ‘ n ≀ 5000, βˆ‘ d ≀ 5000). Output For each test case, print the answer. If it is impossible to construct such a tree, print "NO" (without quotes) in the first line. Otherwise, print "{YES}" in the first line. Then print n-1 integers p_2, p_3, ..., p_n in the second line, where p_i is the parent of the vertex i. Note that the sequence of parents you print should describe some binary tree. Example Input 3 5 7 10 19 10 18 Output YES 1 2 1 3 YES 1 2 3 3 9 9 2 1 6 NO Note Pictures corresponding to the first and the second test cases of the example: <image> <image> Submitted Solution: ``` # 3/2/2020, 8:23 PM # edited to just edit the parent array import math import sys import operator def raise_d(parent): # find the deepest depth that has more than one vertex just_parent = [i for i, j in parent] for deep in range(n): if depth_track[-i - 1] >= 2: break deep_nodes = [] c = 0 for p, depth in parent[::-1]: if depth == deep: deep_nodes.append(n - c) if len(deep_nodes) == 2: break c += 1 # deep_nodes contains vertices at depth = deep for NC in deep_nodes: if just_parent.count(NC) < 2: C ,= [x for x in deep_nodes if x != NC] # now we have NC with at most one child and C the other node # we just have to move C to be a child of NC parent[C] = NC, deep + 1 depth_track[deep + 1] += 1 depth_track[deep] -= 1 return parent T = int(input()) for _ in range(T): # 2 cases: one where we use as little vertices and # another where we fill us levels are much as we can n, d = map(int, input().split()) # upper bound ub = n*(n - 1)//2 # calculating the lower bound count = n depth = 0 lb = 0 while count > 0: depth_count = 2**depth fill = min(count, depth_count) count -= fill lb += fill*depth depth += 1 # testing d against bounds if not (lb <= d <= ub): print ('NO') continue # create an array to keep track of how many nodes are at each depth depth_track = [0]*(n) # create the parent array for lower bound parent = [(-1, -1) for i in range(n + 1)] for i in range(1, n + 1): if i % 2 == 1: p = (i - 1)//2 depth = len(bin(i)) - 3 parent[i] = (p, depth) depth_track[depth] += 1 else: p = i//2 depth = len(bin(i)) - 3 parent[i] = (p, depth) depth_track[depth] += 1 # note that we will only increase the depth of a node, never decrease def raise_d(parent): # find the deepest depth that has more than one vertex just_parent = [i for i, j in parent] for deep in range(n - 1, -1, -1): if depth_track[deep] >= 2: break deep_nodes = [] c = 0 for p, depth in parent[::-1]: if depth == deep: deep_nodes.append(n - c) if len(deep_nodes) == 2: break c += 1 # deep_nodes contains vertices at depth = deep for NC in deep_nodes: if just_parent.count(NC) == 0: C ,= [x for x in deep_nodes if x != NC] break # now we have NC with at most one child and C the other node # we just have to move NC to be a child of C parent[NC] = C, deep + 1 depth_track[deep + 1] += 1 depth_track[deep] -= 1 return parent for i in range(d - lb): parent = raise_d(parent) print ('YES') # making an array so that vertex v at index v - 1 has its parent node there parent = [p for p, depth in parent if depth != 0 and depth != -1] print (*parent) ```
instruction
0
40,554
13
81,108
Yes
output
1
40,554
13
81,109
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given two integers n and d. You need to construct a rooted binary tree consisting of n vertices with a root at the vertex 1 and the sum of depths of all vertices equals to d. A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a vertex v is the last different from v vertex on the path from the root to the vertex v. The depth of the vertex v is the length of the path from the root to the vertex v. Children of vertex v are all vertices for which v is the parent. The binary tree is such a tree that no vertex has more than 2 children. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≀ t ≀ 1000) β€” the number of test cases. The only line of each test case contains two integers n and d (2 ≀ n, d ≀ 5000) β€” the number of vertices in the tree and the required sum of depths of all vertices. It is guaranteed that the sum of n and the sum of d both does not exceed 5000 (βˆ‘ n ≀ 5000, βˆ‘ d ≀ 5000). Output For each test case, print the answer. If it is impossible to construct such a tree, print "NO" (without quotes) in the first line. Otherwise, print "{YES}" in the first line. Then print n-1 integers p_2, p_3, ..., p_n in the second line, where p_i is the parent of the vertex i. Note that the sequence of parents you print should describe some binary tree. Example Input 3 5 7 10 19 10 18 Output YES 1 2 1 3 YES 1 2 3 3 9 9 2 1 6 NO Note Pictures corresponding to the first and the second test cases of the example: <image> <image> Submitted Solution: ``` # 3/2/2020, 8:23 PM # edited to just edit the parent array import math import sys import operator def raise_d(parent): # find the deepest depth that has more than one vertex just_parent = [i for i, j in parent] for deep in range(n): if depth_track[-i - 1] >= 2: break deep_nodes = [] c = 0 for p, depth in parent[::-1]: if depth == deep: deep_nodes.append(n - c) if len(deep_nodes) == 2: break c += 1 # deep_nodes contains vertices at depth = deep for NC in deep_nodes: if just_parent.count(NC) < 2: C ,= [x for x in deep_nodes if x != NC] # now we have NC with at most one child and C the other node # we just have to move C to be a child of NC parent[C] = NC, deep + 1 depth_track[deep + 1] += 1 depth_track[deep] -= 1 return parent T = int(input()) for _ in range(T): # 2 cases: one where we use as little vertices and # another where we fill us levels are much as we can n, d = map(int, input().split()) # upper bound ub = n*(n - 1)//2 # calculating the lower bound count = n depth = 0 lb = 0 while count > 0: depth_count = 2**depth fill = min(count, depth_count) count -= fill lb += fill*depth depth += 1 # testing d against bounds if not (lb <= d <= ub): print ('NO') continue # create an array to keep track of how many nodes are at each depth depth_track = [0]*(n) # create the parent array for lower bound parent = [(-1, -1) for i in range(n + 1)] for i in range(1, n + 1): if i % 2 == 1: p = (i - 1)//2 depth = len(bin(i)) - 3 parent[i] = (p, depth) depth_track[depth] += 1 else: p = i//2 depth = len(bin(i)) - 3 parent[i] = (p, depth) depth_track[depth] += 1 # note that we will only increase the depth of a node, never decrease def raise_d(parent): # find the deepest depth that has more than one vertex just_parent = [i for i, j in parent] for deep in range(n - 1, -1, -1): if depth_track[deep] >= 2: break deep_nodes = [] c = 0 for p, depth in parent[::-1]: if depth == deep: deep_nodes.append(n - c) if len(deep_nodes) == 2: break c += 1 # deep_nodes contains vertices at depth = deep for NC in deep_nodes: if just_parent.count(NC) in (0, 1): C ,= [x for x in deep_nodes if x != NC] # now we have NC with at most one child and C the other node # we just have to move C to be a child of NC parent[NC] = C, deep + 1 depth_track[deep + 1] += 1 depth_track[deep] -= 1 return parent for i in range(d - lb): parent = raise_d(parent) print ('YES') # making an array so that vertex v at index v - 1 has its parent node there parent = [p for p, depth in parent if depth != 0 and depth != -1] print (*parent) ```
instruction
0
40,555
13
81,110
No
output
1
40,555
13
81,111
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given two integers n and d. You need to construct a rooted binary tree consisting of n vertices with a root at the vertex 1 and the sum of depths of all vertices equals to d. A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a vertex v is the last different from v vertex on the path from the root to the vertex v. The depth of the vertex v is the length of the path from the root to the vertex v. Children of vertex v are all vertices for which v is the parent. The binary tree is such a tree that no vertex has more than 2 children. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≀ t ≀ 1000) β€” the number of test cases. The only line of each test case contains two integers n and d (2 ≀ n, d ≀ 5000) β€” the number of vertices in the tree and the required sum of depths of all vertices. It is guaranteed that the sum of n and the sum of d both does not exceed 5000 (βˆ‘ n ≀ 5000, βˆ‘ d ≀ 5000). Output For each test case, print the answer. If it is impossible to construct such a tree, print "NO" (without quotes) in the first line. Otherwise, print "{YES}" in the first line. Then print n-1 integers p_2, p_3, ..., p_n in the second line, where p_i is the parent of the vertex i. Note that the sequence of parents you print should describe some binary tree. Example Input 3 5 7 10 19 10 18 Output YES 1 2 1 3 YES 1 2 3 3 9 9 2 1 6 NO Note Pictures corresponding to the first and the second test cases of the example: <image> <image> Submitted Solution: ``` for tests in range(int(input())): n, d = map(int,input().split()) upper_bound, lower_bound, lv = n * (n - 1) // 2, 0, 0 for i in range(1, n + 1): if not(i & (i - 1)): lv += 1 lower_bound += lv - 1 if not(d in range(lower_bound, upper_bound + 1)): print("NO") else: bad = [False] * n depth = list(range(n)) count_child = [1] * n count_child[n - 1] = 0 current_depth = upper_bound parent = list(range(-1,n-1)) while current_depth > d: v, p = -1, -1 for i in range(n): if not(bad[i]) and count_child[i] == 0 and (v == -1 or depth[i] < depth[v]): v = i for i in range(n): if count_child[i] < 2 and depth[i] == depth[v] - 2 and (p == -1 or depth[i] > depth[p]): p = i if p == -1: bad[v] = True continue count_child[parent[v]] -= 1 depth[v] -= 1 count_child[p] += 1 parent[v] = p current_depth -= 1 print("YES") print(*(parent[i] for i in range(1,n))) ```
instruction
0
40,556
13
81,112
No
output
1
40,556
13
81,113
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given two integers n and d. You need to construct a rooted binary tree consisting of n vertices with a root at the vertex 1 and the sum of depths of all vertices equals to d. A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a vertex v is the last different from v vertex on the path from the root to the vertex v. The depth of the vertex v is the length of the path from the root to the vertex v. Children of vertex v are all vertices for which v is the parent. The binary tree is such a tree that no vertex has more than 2 children. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≀ t ≀ 1000) β€” the number of test cases. The only line of each test case contains two integers n and d (2 ≀ n, d ≀ 5000) β€” the number of vertices in the tree and the required sum of depths of all vertices. It is guaranteed that the sum of n and the sum of d both does not exceed 5000 (βˆ‘ n ≀ 5000, βˆ‘ d ≀ 5000). Output For each test case, print the answer. If it is impossible to construct such a tree, print "NO" (without quotes) in the first line. Otherwise, print "{YES}" in the first line. Then print n-1 integers p_2, p_3, ..., p_n in the second line, where p_i is the parent of the vertex i. Note that the sequence of parents you print should describe some binary tree. Example Input 3 5 7 10 19 10 18 Output YES 1 2 1 3 YES 1 2 3 3 9 9 2 1 6 NO Note Pictures corresponding to the first and the second test cases of the example: <image> <image> Submitted Solution: ``` import math T = int(input()) n = [0]*T d = [0]*T for t in range(T): n[t],d[t] = [int(i) for i in input().split(' ')] def f(n): return int(0.5*(n*n+n)) def g(n): a= 0 ln = int(math.log(n)) a+=sum([i*(2**i) for i in range(1,ln+1)]) a+= (n-(2**(ln+1)-1))*(ln+1) return a def bmd(m): if m[-1] != 1: print('WATCH OUT M[-1] != 1') for i in range(len(m)): if m[i]<2**i: return len(m)-i-1 def evalT(m): a = 0 for i in range(len(m)): a+=i*m[i] return a def enbmd(m): if m[-1] != 1: print('WATCH OUT M[-1] != 1') m.pop(-1) for i in range(len(m)): if m[i]<2**i: m[i]+=1 return len(m)-i-1 def ans(n,d): m = [1]*n if d>f(n-1) or d<g(n): return 'NO' print('YES') T = f(n-1) while T!=d: if T-d>=bmd(m): enbmd(m) else: m.pop(-1) m[T-d-len(m)+1]+=1 break T = evalT(m) n = 1 sw = 0 for i in range(len(m)-1): for j in range(m[i+1]): print(n,end=' ') if sw: n+=1 sw^=1 if sw: n+=1 return m for t in range(T): print(ans(n[t],d[t])) ```
instruction
0
40,557
13
81,114
No
output
1
40,557
13
81,115
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given two integers n and d. You need to construct a rooted binary tree consisting of n vertices with a root at the vertex 1 and the sum of depths of all vertices equals to d. A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a vertex v is the last different from v vertex on the path from the root to the vertex v. The depth of the vertex v is the length of the path from the root to the vertex v. Children of vertex v are all vertices for which v is the parent. The binary tree is such a tree that no vertex has more than 2 children. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≀ t ≀ 1000) β€” the number of test cases. The only line of each test case contains two integers n and d (2 ≀ n, d ≀ 5000) β€” the number of vertices in the tree and the required sum of depths of all vertices. It is guaranteed that the sum of n and the sum of d both does not exceed 5000 (βˆ‘ n ≀ 5000, βˆ‘ d ≀ 5000). Output For each test case, print the answer. If it is impossible to construct such a tree, print "NO" (without quotes) in the first line. Otherwise, print "{YES}" in the first line. Then print n-1 integers p_2, p_3, ..., p_n in the second line, where p_i is the parent of the vertex i. Note that the sequence of parents you print should describe some binary tree. Example Input 3 5 7 10 19 10 18 Output YES 1 2 1 3 YES 1 2 3 3 9 9 2 1 6 NO Note Pictures corresponding to the first and the second test cases of the example: <image> <image> Submitted Solution: ``` t=int(input()) for q in range(t): n,d=map(int,input().split()) l=1 i=1 s=[] ans=[1] x=bin(n) while len(s)<n and d: if d>=(l*(2**l)): d-= l*(2**l) if s: s+=[l+1]*(2**l) else: s=[1]*(2**l) else: x=min(n-i,d//(l)) d-=(x)*(l) if d and d<l+1: d+=x x-=1 if s: s+=[l+1]*(x) else: s=[1]*(x) l+=1 if len(s)==n-1 and d==0: print("YES") print(*s) else: print("NO") ```
instruction
0
40,558
13
81,116
No
output
1
40,558
13
81,117
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an undirected graph without self-loops or multiple edges which consists of n vertices and m edges. Also you are given three integers n_1, n_2 and n_3. Can you label each vertex with one of three numbers 1, 2 or 3 in such way, that: 1. Each vertex should be labeled by exactly one number 1, 2 or 3; 2. The total number of vertices with label 1 should be equal to n_1; 3. The total number of vertices with label 2 should be equal to n_2; 4. The total number of vertices with label 3 should be equal to n_3; 5. |col_u - col_v| = 1 for each edge (u, v), where col_x is the label of vertex x. If there are multiple valid labelings, print any of them. Input The first line contains two integers n and m (1 ≀ n ≀ 5000; 0 ≀ m ≀ 10^5) β€” the number of vertices and edges in the graph. The second line contains three integers n_1, n_2 and n_3 (0 ≀ n_1, n_2, n_3 ≀ n) β€” the number of labels 1, 2 and 3, respectively. It's guaranteed that n_1 + n_2 + n_3 = n. Next m lines contan description of edges: the i-th line contains two integers u_i, v_i (1 ≀ u_i, v_i ≀ n; u_i β‰  v_i) β€” the vertices the i-th edge connects. It's guaranteed that the graph doesn't contain self-loops or multiple edges. Output If valid labeling exists then print "YES" (without quotes) in the first line. In the second line print string of length n consisting of 1, 2 and 3. The i-th letter should be equal to the label of the i-th vertex. If there is no valid labeling, print "NO" (without quotes). Examples Input 6 3 2 2 2 3 1 5 4 2 5 Output YES 112323 Input 5 9 0 2 3 1 2 1 3 1 5 2 3 2 4 2 5 3 4 3 5 4 5 Output NO
instruction
0
40,575
13
81,150
Tags: dfs and similar, dp, graphs Correct Solution: ``` n,m = map(int, input().split()) x, y, z = map(int, input().split()) ed = [] for _ in range(n): ed.append([]) for _ in range(m): a, b = map(int, input().split()) a -= 1 b -= 1 ed[a].append(b) ed[b].append(a) cl = [0] * n def bfs(v, c): cl[v] = c h = w = 0 if c == 1: h = 1 else: w = 1 for i in ed[v]: if cl[i] == c: return [False, h, w] elif cl[i] == 0: f, hh, ww = bfs(i, -c) h += hh w += ww if not f: return [False, h, w] return [True, h, w] q = [] for i in range(n): if cl[i]==0: f,h,w=bfs(i,1) if not f:exit(print("NO")) q.append([i,min(h,w),max(h,w)-min(h,w),1-2*(h<w)]) yy=y for _,i,__,___ in q:yy-=i if yy<0:exit(print("NO")) dp=[(yy+1)*[0]for _ in range(len(q)+1)] dp[0][0]=1 for i in range(len(q)): _,__,ii,___=q[i] for j in range(yy+1):dp[i+1][j]=dp[i][j] for j in range(yy+1): if ii+j>yy:break dp[i+1][ii+j]|=dp[i][j] if dp[-1][-1]==0:exit(print("NO")) k=yy qq=[] for i in range(len(q),0,-1): if dp[i][k]==dp[i-1][k]:qq.append((q[i-1][0],-q[i-1][3])) else: qq.append((q[i-1][0],q[i-1][3])) k-=q[i-1][2] cl=[0]*n visited=set() for i,c in qq: stack=[i] visited.add(i) cl[i]=c for j in stack: for k in ed[j]: if k in visited:continue visited.add(k) cl[k]=-cl[j] stack.append(k) for i in range(n): if cl[i]==1:cl[i]="2" elif x:cl[i]="1";x-=1 else:cl[i]="3" print("YES") print("".join(cl)) ```
output
1
40,575
13
81,151
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an undirected graph without self-loops or multiple edges which consists of n vertices and m edges. Also you are given three integers n_1, n_2 and n_3. Can you label each vertex with one of three numbers 1, 2 or 3 in such way, that: 1. Each vertex should be labeled by exactly one number 1, 2 or 3; 2. The total number of vertices with label 1 should be equal to n_1; 3. The total number of vertices with label 2 should be equal to n_2; 4. The total number of vertices with label 3 should be equal to n_3; 5. |col_u - col_v| = 1 for each edge (u, v), where col_x is the label of vertex x. If there are multiple valid labelings, print any of them. Input The first line contains two integers n and m (1 ≀ n ≀ 5000; 0 ≀ m ≀ 10^5) β€” the number of vertices and edges in the graph. The second line contains three integers n_1, n_2 and n_3 (0 ≀ n_1, n_2, n_3 ≀ n) β€” the number of labels 1, 2 and 3, respectively. It's guaranteed that n_1 + n_2 + n_3 = n. Next m lines contan description of edges: the i-th line contains two integers u_i, v_i (1 ≀ u_i, v_i ≀ n; u_i β‰  v_i) β€” the vertices the i-th edge connects. It's guaranteed that the graph doesn't contain self-loops or multiple edges. Output If valid labeling exists then print "YES" (without quotes) in the first line. In the second line print string of length n consisting of 1, 2 and 3. The i-th letter should be equal to the label of the i-th vertex. If there is no valid labeling, print "NO" (without quotes). Examples Input 6 3 2 2 2 3 1 5 4 2 5 Output YES 112323 Input 5 9 0 2 3 1 2 1 3 1 5 2 3 2 4 2 5 3 4 3 5 4 5 Output NO
instruction
0
40,576
13
81,152
Tags: dfs and similar, dp, graphs Correct Solution: ``` import sys;input=sys.stdin.readline N, M = map(int, input().split()) n1, n2, n3 = map(int, input().split()) G = [set() for _ in range(N+1)] for _ in range(M): u, v = map(int, input().split()) G[u].add(v) G[v].add(u) cl = [-1 for _ in range(N+1)] vs = set() Y = [] for i in range(1, N+1): if i in vs: continue cl[i] = 0 tmp = [[i], []] stack = [i] vs.add(i) while stack: v = stack.pop() for u in G[v]: if cl[u] == cl[v]: print("NO") sys.exit() if u in vs: continue cl[u] = 1-cl[v] tmp[cl[u]].append(u) vs.add(u) stack.append(u) Y.append(tmp) k = len(Y) dp = [[0]*(N+1) for _ in range(k+1)] dp[0][0] = 1 for i in range(k): y1, y2 = len(Y[i][0]), len(Y[i][1]) for j in range(N, -1, -1): tmp = 0 if j-y1>=0: tmp = dp[i][j-y1] if j-y2>=0: tmp = dp[i][j-y2] | tmp dp[i+1][j] = tmp if dp[-1][n2] == 0: print("NO") sys.exit() mch = n2 ans = [0] * (N+1) for i in range(k-1, -1, -1): y1, y2 = len(Y[i][0]), len(Y[i][1]) if mch>=y1 and dp[i][mch-y1]: for u in Y[i][0]: ans[u] = 2 for u in Y[i][1]: if n1 > 0: ans[u] = 1 n1 -= 1 else: ans[u] = 3 mch -= y1 else: for u in Y[i][0]: if n1 > 0: ans[u] = 1 n1 -= 1 else: ans[u] = 3 for u in Y[i][1]: ans[u] = 2 mch -= y2 print("YES") print("".join(str(u) for u in ans[1:])) ```
output
1
40,576
13
81,153
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an undirected graph without self-loops or multiple edges which consists of n vertices and m edges. Also you are given three integers n_1, n_2 and n_3. Can you label each vertex with one of three numbers 1, 2 or 3 in such way, that: 1. Each vertex should be labeled by exactly one number 1, 2 or 3; 2. The total number of vertices with label 1 should be equal to n_1; 3. The total number of vertices with label 2 should be equal to n_2; 4. The total number of vertices with label 3 should be equal to n_3; 5. |col_u - col_v| = 1 for each edge (u, v), where col_x is the label of vertex x. If there are multiple valid labelings, print any of them. Input The first line contains two integers n and m (1 ≀ n ≀ 5000; 0 ≀ m ≀ 10^5) β€” the number of vertices and edges in the graph. The second line contains three integers n_1, n_2 and n_3 (0 ≀ n_1, n_2, n_3 ≀ n) β€” the number of labels 1, 2 and 3, respectively. It's guaranteed that n_1 + n_2 + n_3 = n. Next m lines contan description of edges: the i-th line contains two integers u_i, v_i (1 ≀ u_i, v_i ≀ n; u_i β‰  v_i) β€” the vertices the i-th edge connects. It's guaranteed that the graph doesn't contain self-loops or multiple edges. Output If valid labeling exists then print "YES" (without quotes) in the first line. In the second line print string of length n consisting of 1, 2 and 3. The i-th letter should be equal to the label of the i-th vertex. If there is no valid labeling, print "NO" (without quotes). Examples Input 6 3 2 2 2 3 1 5 4 2 5 Output YES 112323 Input 5 9 0 2 3 1 2 1 3 1 5 2 3 2 4 2 5 3 4 3 5 4 5 Output NO
instruction
0
40,577
13
81,154
Tags: dfs and similar, dp, graphs Correct Solution: ``` import sys input = sys.stdin.buffer.readline N, M = map(int, input().split()) n1, n2, n3 = map(int, input().split()) graph = [[] for _ in range(N)] for _ in range(M): a, b = map(int, input().split()) graph[a-1].append(b-1) graph[b-1].append(a-1) def check(): Color = [-1]*N P = [] ok = True for n in range(N): if Color[n] != -1: continue q = [n] Color[n] = 0 Cs = [[n], []] while q: qq = [] for p in q: for np in graph[p]: if Color[np] == -1: qq.append(np) Color[np] = Color[p]^1 Cs[Color[np]].append(np) elif Color[np] != Color[p]^1: ok = False break q = qq P.append(Cs) return ok, P def main(): ok, P = check() dp = [[None]*(n2+1) for _ in range(len(P)+1)] dp[0][0] = 0 for i in range(len(P)): a = len(P[i][0]); b = len(P[i][1]) for n in range(n2+1): if not dp[i][n] is None: if n+a <= n2: dp[i+1][n+a] = ~a if n+b <= n2: dp[i+1][n+b] = b if not ok or dp[-1][n2] is None: print("NO") else: print("YES") tmp = n2 Use2 = [-1]*N for i in reversed(range(len(P))): leng = dp[i+1][tmp] label = 1 if leng < 0: label = 0 leng = ~leng for n in P[i][label]: Use2[n] = 1 for n in P[i][label^1]: Use2[n] = 0 tmp -= leng ans = [] num1 = 0 for n, use2 in enumerate(Use2): if use2: ans.append("2") elif num1 < n1: num1 += 1 ans.append("1") else: ans.append("3") print("".join(ans)) if __name__ == "__main__": main() ```
output
1
40,577
13
81,155
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an undirected graph without self-loops or multiple edges which consists of n vertices and m edges. Also you are given three integers n_1, n_2 and n_3. Can you label each vertex with one of three numbers 1, 2 or 3 in such way, that: 1. Each vertex should be labeled by exactly one number 1, 2 or 3; 2. The total number of vertices with label 1 should be equal to n_1; 3. The total number of vertices with label 2 should be equal to n_2; 4. The total number of vertices with label 3 should be equal to n_3; 5. |col_u - col_v| = 1 for each edge (u, v), where col_x is the label of vertex x. If there are multiple valid labelings, print any of them. Input The first line contains two integers n and m (1 ≀ n ≀ 5000; 0 ≀ m ≀ 10^5) β€” the number of vertices and edges in the graph. The second line contains three integers n_1, n_2 and n_3 (0 ≀ n_1, n_2, n_3 ≀ n) β€” the number of labels 1, 2 and 3, respectively. It's guaranteed that n_1 + n_2 + n_3 = n. Next m lines contan description of edges: the i-th line contains two integers u_i, v_i (1 ≀ u_i, v_i ≀ n; u_i β‰  v_i) β€” the vertices the i-th edge connects. It's guaranteed that the graph doesn't contain self-loops or multiple edges. Output If valid labeling exists then print "YES" (without quotes) in the first line. In the second line print string of length n consisting of 1, 2 and 3. The i-th letter should be equal to the label of the i-th vertex. If there is no valid labeling, print "NO" (without quotes). Examples Input 6 3 2 2 2 3 1 5 4 2 5 Output YES 112323 Input 5 9 0 2 3 1 2 1 3 1 5 2 3 2 4 2 5 3 4 3 5 4 5 Output NO
instruction
0
40,578
13
81,156
Tags: dfs and similar, dp, graphs Correct Solution: ``` from sys import stdin, gettrace from collections import deque if not gettrace(): def input(): return next(stdin)[:-1] # def input(): # return stdin.buffer.readline() def main(): n,m = map(int, input().split()) n1, n2, n3 = map(int, input().split()) adj = [[] for _ in range(n)] for _ in range(m): u,v = map(int, input().split()) adj[u-1].append(v-1) adj[v-1].append(u-1) components = [] grp = [-1] * n for i in range(n): if grp[i] == -1: q = deque() q.append(i) grp[i] = 0 components.append([[i], []]) while q: u = q.popleft() for v in adj[u]: if grp[v] == -1: grp[v] = 1 - grp[u] components[-1][grp[v]].append(v) q.append(v) elif grp[v] == grp[u]: print("NO") return dp = [[0 for _ in range(n+2)] for _ in range(len(components))] dp[0][len(components[0][0])+1] = -1 dp[0][len(components[0][1])+1] = 1 for i, comp in enumerate(components[1:]): l0 = len(comp[0]) l1 = len(comp[1]) for j in range(1, n2+2): if dp[i][j]: dp[i+1][j+l0] = -j dp[i+1][j+l1] = j if not dp[-1][n2+1]: print("NO") return print("YES") j = n2+1 colour = ['x'] * n for i in range(len(components)-1, -1, -1): g = 0 if dp[i][j] < 0 else 1 j = abs(dp[i][j]) for u in components[i][g]: colour[u] = '2' for u in components[i][1-g]: if n1 > 0: colour[u] = '1' n1 -= 1 else: colour[u] = '3' print(''.join(colour)) if __name__ == "__main__": main() ```
output
1
40,578
13
81,157
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an undirected graph without self-loops or multiple edges which consists of n vertices and m edges. Also you are given three integers n_1, n_2 and n_3. Can you label each vertex with one of three numbers 1, 2 or 3 in such way, that: 1. Each vertex should be labeled by exactly one number 1, 2 or 3; 2. The total number of vertices with label 1 should be equal to n_1; 3. The total number of vertices with label 2 should be equal to n_2; 4. The total number of vertices with label 3 should be equal to n_3; 5. |col_u - col_v| = 1 for each edge (u, v), where col_x is the label of vertex x. If there are multiple valid labelings, print any of them. Input The first line contains two integers n and m (1 ≀ n ≀ 5000; 0 ≀ m ≀ 10^5) β€” the number of vertices and edges in the graph. The second line contains three integers n_1, n_2 and n_3 (0 ≀ n_1, n_2, n_3 ≀ n) β€” the number of labels 1, 2 and 3, respectively. It's guaranteed that n_1 + n_2 + n_3 = n. Next m lines contan description of edges: the i-th line contains two integers u_i, v_i (1 ≀ u_i, v_i ≀ n; u_i β‰  v_i) β€” the vertices the i-th edge connects. It's guaranteed that the graph doesn't contain self-loops or multiple edges. Output If valid labeling exists then print "YES" (without quotes) in the first line. In the second line print string of length n consisting of 1, 2 and 3. The i-th letter should be equal to the label of the i-th vertex. If there is no valid labeling, print "NO" (without quotes). Examples Input 6 3 2 2 2 3 1 5 4 2 5 Output YES 112323 Input 5 9 0 2 3 1 2 1 3 1 5 2 3 2 4 2 5 3 4 3 5 4 5 Output NO
instruction
0
40,579
13
81,158
Tags: dfs and similar, dp, graphs Correct Solution: ``` mod = 1000000007 eps = 10**-9 def main(): import sys from collections import deque input = sys.stdin.buffer.readline N, M = map(int, input().split()) n1, n2, n3 = map(int, input().split()) adj = [[] for _ in range(N+1)] for _ in range(M): a, b = map(int, input().split()) adj[a].append(b) adj[b].append(a) seen = [-1] * (N+1) BW = [] for v0 in range(1, N+1): if seen[v0] != -1: continue que = deque() que.append(v0) seen[v0] = 0 B = [v0] W = [] while que: v = que.popleft() for u in adj[v]: if seen[u] == -1: seen[u] = seen[v] ^ 1 if seen[u] == 0: B.append(u) else: W.append(u) que.append(u) else: if seen[u] == seen[v]: print("NO") exit() BW.append((B, W)) G = len(BW) dp = [[0] * (n2+1) for _ in range(G+1)] dp[0][0] = 1 for i in range(G): b = len(BW[i][0]) w = len(BW[i][1]) for j in range(n2+1): if dp[i][j]: if j+b <= n2: dp[i+1][j+b] = 1 if j+w <= n2: dp[i+1][j+w] = 1 if not dp[-1][n2]: print("NO") exit() val = n2 ans = [0] * (N+1) for i in range(G-1, -1, -1): b = len(BW[i][0]) w = len(BW[i][1]) ok = 0 if val - b >= 0: if dp[i][val - b]: val -= b for v in BW[i][0]: ans[v] = 2 ok = 1 if not ok: if val - w >= 0: if dp[i][val - w]: val -= w for v in BW[i][1]: ans[v] = 2 flg = n1 for i in range(1, N+1): if ans[i] == 0: if flg: ans[i] = 1 flg -= 1 else: ans[i] = 3 print("YES") print("".join(map(str, ans[1:]))) if __name__ == '__main__': main() ```
output
1
40,579
13
81,159
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an undirected graph without self-loops or multiple edges which consists of n vertices and m edges. Also you are given three integers n_1, n_2 and n_3. Can you label each vertex with one of three numbers 1, 2 or 3 in such way, that: 1. Each vertex should be labeled by exactly one number 1, 2 or 3; 2. The total number of vertices with label 1 should be equal to n_1; 3. The total number of vertices with label 2 should be equal to n_2; 4. The total number of vertices with label 3 should be equal to n_3; 5. |col_u - col_v| = 1 for each edge (u, v), where col_x is the label of vertex x. If there are multiple valid labelings, print any of them. Input The first line contains two integers n and m (1 ≀ n ≀ 5000; 0 ≀ m ≀ 10^5) β€” the number of vertices and edges in the graph. The second line contains three integers n_1, n_2 and n_3 (0 ≀ n_1, n_2, n_3 ≀ n) β€” the number of labels 1, 2 and 3, respectively. It's guaranteed that n_1 + n_2 + n_3 = n. Next m lines contan description of edges: the i-th line contains two integers u_i, v_i (1 ≀ u_i, v_i ≀ n; u_i β‰  v_i) β€” the vertices the i-th edge connects. It's guaranteed that the graph doesn't contain self-loops or multiple edges. Output If valid labeling exists then print "YES" (without quotes) in the first line. In the second line print string of length n consisting of 1, 2 and 3. The i-th letter should be equal to the label of the i-th vertex. If there is no valid labeling, print "NO" (without quotes). Examples Input 6 3 2 2 2 3 1 5 4 2 5 Output YES 112323 Input 5 9 0 2 3 1 2 1 3 1 5 2 3 2 4 2 5 3 4 3 5 4 5 Output NO
instruction
0
40,580
13
81,160
Tags: dfs and similar, dp, graphs Correct Solution: ``` import sys input = sys.stdin.readline from collections import * def bfs(s): color[s] = 1 q = deque([s]) d[s][1].append(s) while q: v = q.popleft() for nv in G[v]: if color[nv]==0: color[nv] = -color[v] q.append(nv) if color[nv]==1: d[s][1].append(nv) else: d[s][0].append(nv) else: if color[nv]==color[v]: return -1, -1 return len(d[s][1]), len(d[s][0]) n, m = map(int, input().split()) n1, n2, n3 = map(int, input().split()) G = [[] for _ in range(n)] for _ in range(m): u, v = map(int, input().split()) G[u-1].append(v-1) G[v-1].append(u-1) d = defaultdict(lambda : defaultdict(list)) color = [0]*n sta = [] bw = [] for i in range(n): if color[i]==0: b, w = bfs(i) if b==-1: print('NO') exit() sta.append(i) bw.append((b, w)) dp = [[-1]*(n+1) for _ in range(len(bw)+1)] dp[0][0] = True for i in range(len(bw)): for j in range(n+1): if dp[i][j]==-1: continue dp[i+1][j+bw[i][0]] = 0 dp[i+1][j+bw[i][1]] = 1 if dp[-1][n2]==-1: print('NO') exit() ans = ['']*n for i in range(len(bw), 0, -1): if dp[i][n2]==0: for v in d[sta[i-1]][1]: ans[v] = '2' n2 -= bw[i-1][0] else: for v in d[sta[i-1]][0]: ans[v] = '2' n2 -= bw[i-1][1] for v in range(n): if ans[v]=='': if n1>0: ans[v] = '1' n1 -= 1 else: ans[v] = '3' print('YES') print(''.join(ans)) ```
output
1
40,580
13
81,161
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an undirected graph without self-loops or multiple edges which consists of n vertices and m edges. Also you are given three integers n_1, n_2 and n_3. Can you label each vertex with one of three numbers 1, 2 or 3 in such way, that: 1. Each vertex should be labeled by exactly one number 1, 2 or 3; 2. The total number of vertices with label 1 should be equal to n_1; 3. The total number of vertices with label 2 should be equal to n_2; 4. The total number of vertices with label 3 should be equal to n_3; 5. |col_u - col_v| = 1 for each edge (u, v), where col_x is the label of vertex x. If there are multiple valid labelings, print any of them. Input The first line contains two integers n and m (1 ≀ n ≀ 5000; 0 ≀ m ≀ 10^5) β€” the number of vertices and edges in the graph. The second line contains three integers n_1, n_2 and n_3 (0 ≀ n_1, n_2, n_3 ≀ n) β€” the number of labels 1, 2 and 3, respectively. It's guaranteed that n_1 + n_2 + n_3 = n. Next m lines contan description of edges: the i-th line contains two integers u_i, v_i (1 ≀ u_i, v_i ≀ n; u_i β‰  v_i) β€” the vertices the i-th edge connects. It's guaranteed that the graph doesn't contain self-loops or multiple edges. Output If valid labeling exists then print "YES" (without quotes) in the first line. In the second line print string of length n consisting of 1, 2 and 3. The i-th letter should be equal to the label of the i-th vertex. If there is no valid labeling, print "NO" (without quotes). Examples Input 6 3 2 2 2 3 1 5 4 2 5 Output YES 112323 Input 5 9 0 2 3 1 2 1 3 1 5 2 3 2 4 2 5 3 4 3 5 4 5 Output NO
instruction
0
40,581
13
81,162
Tags: dfs and similar, dp, graphs Correct Solution: ``` import os import sys if os.path.exists('/mnt/c/Users/Square/square/codeforces'): f = iter(open('E.txt').readlines()) def input(): return next(f).strip() # input = lambda: sys.stdin.readline().strip() else: input = lambda: sys.stdin.readline() fprint = lambda *args: print(*args, flush=True) import math try: n, m = map(int, input().split()) g = {i : [] for i in range(n+1)} n1, n2, n3 = map(int, input().split()) c = [-1] * (n+1) for _ in range(m): u, v = map(int, input().split()) g[u].append(v) g[v].append(u) num = 0 S = [] V = [] for i in range(1, n+1): if c[i] == -1: r = [0] * 2 tmp = [[], []] c[i] = num r[c[i] % 2] += 1 tmp[c[i] % 2].append(i) stack = [i] while stack: u = stack.pop() for v in g[u]: if c[v] == -1: c[v] = num + (c[u]+1) % 2 r[c[v] % 2] += 1 tmp[c[v] % 2].append(v) stack.append(v) elif c[u] == c[v]: raise RuntimeError num += 10 S.append(r) V.append(tmp) # print(S) N = (n+1) s = len(S)+1 d = [-2] * (N * s) d[0] = -1 for lev, (r1, r2) in enumerate(S): # print(r1, r2) add = lev * N + N for i in range(n): # d[lev * N] = -1 if d[i + lev * N] != -2: d[i+r1 + add] = lev d[i+r2 + add] = lev # for i in range(s): # print(d[N*i:N*i+N]) if d[N*(s-1) + n2] == -2: raise RuntimeError cur = n2 ords = [] for lev, (r1, r2) in reversed(list(enumerate(S))): # print(d[add:add+N], lev) add = lev * N if cur - r1 >= 0 and d[add + cur - r1] == lev-1: ords.append(0) cur -= r1 else: ords.append(1) cur -= r2 ords = list(reversed(ords)) # print(ords) # print(V) colors = ['0'] * (n+1) for o, r in zip(ords, V): for col in r[o]: colors[col] = '2' for i in range(1, n+1): if colors[i] == '0': if n1 > 0: colors[i] = '1' n1 -= 1 else: colors[i] = '3' print('YES') print(''.join(colors[1:])) # print(d) # for r1, r2 in S: # if d[] except RuntimeError: print('NO') ```
output
1
40,581
13
81,163