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. As the name of the task implies, you are asked to do some work with segments and trees. Recall that a tree is a connected undirected graph such that there is exactly one simple path between every pair of its vertices. You are given n segments [l_1, r_1], [l_2, r_2], ..., [l_n, r_n], l_i < r_i for every i. It is guaranteed that all segments' endpoints are integers, and all endpoints are unique — there is no pair of segments such that they start in the same point, end in the same point or one starts in the same point the other one ends. Let's generate a graph with n vertices from these segments. Vertices v and u are connected by an edge if and only if segments [l_v, r_v] and [l_u, r_u] intersect and neither of it lies fully inside the other one. For example, pairs ([1, 3], [2, 4]) and ([5, 10], [3, 7]) will induce the edges but pairs ([1, 2], [3, 4]) and ([5, 7], [3, 10]) will not. Determine if the resulting graph is a tree or not. Input The first line contains a single integer n (1 ≤ n ≤ 5 ⋅ 10^5) — the number of segments. The i-th of the next n lines contain the description of the i-th segment — two integers l_i and r_i (1 ≤ l_i < r_i ≤ 2n). It is guaranteed that all segments borders are pairwise distinct. Output Print "YES" if the resulting graph is a tree and "NO" otherwise. Examples Input 6 9 12 2 11 1 3 6 10 5 7 4 8 Output YES Input 5 1 3 2 4 5 9 6 8 7 10 Output NO Input 5 5 8 3 6 2 9 7 10 1 4 Output NO Note The graph corresponding to the first example: <image> The graph corresponding to the second example: <image> The graph corresponding to the third example: <image>
instruction
0
70,850
13
141,700
Tags: data structures, dsu, graphs, trees Correct Solution: ``` import sys class BIT(): def __init__(self, n): self.n = n self.tree = [0] * n def _F(self, i): return i & (i + 1) def _getSum(self, r): result = 0 while r >= 0: result += self.tree[r] r = self._F(r) - 1 return result def getSum(self, l, r): return self._getSum(r) - self._getSum(l - 1) def _H(self, i): return i | (i + 1) def add(self, i, value): while i < self.n: self.tree[i] += value i = self._H(i) # inf = open('input.txt', 'r') # reader = (line.rstrip() for line in inf) reader = (line.rstrip() for line in sys.stdin) input = reader.__next__ n = int(input()) segm = [0] * (2 * n + 1) edge = [0] * (2 * n + 1) for i in range(n): l, r = map(int, input().split()) segm[l] = segm[r] = i edge[l] = edge[r] = r # inf.close() opened = BIT(2 * n + 1) g = [[] for _ in range(n)] ctr = 0 for e in range(1, 2 * n + 1): r = edge[e] if e == r: opened.add(e, -1) else: opened.add(r, 1) add = opened.getSum(0, r - 1) ctr += add if ctr > n - 1: print('NO') sys.exit() for k in range(add): L = 0 R = r - 1 while L + 1 < R: m = (L + R) >> 1 if opened.getSum(0, m) > k: R = m else: L = m i = segm[e] j = segm[R] g[i].append(j) g[j].append(i) # print(g) visited = [False] * n stack = [0] while stack: v = stack.pop() if not visited[v]: visited[v] = True for to in g[v]: stack.append(to) print('YES' if all(visited) else 'NO') ```
output
1
70,850
13
141,701
Provide tags and a correct Python 3 solution for this coding contest problem. As the name of the task implies, you are asked to do some work with segments and trees. Recall that a tree is a connected undirected graph such that there is exactly one simple path between every pair of its vertices. You are given n segments [l_1, r_1], [l_2, r_2], ..., [l_n, r_n], l_i < r_i for every i. It is guaranteed that all segments' endpoints are integers, and all endpoints are unique — there is no pair of segments such that they start in the same point, end in the same point or one starts in the same point the other one ends. Let's generate a graph with n vertices from these segments. Vertices v and u are connected by an edge if and only if segments [l_v, r_v] and [l_u, r_u] intersect and neither of it lies fully inside the other one. For example, pairs ([1, 3], [2, 4]) and ([5, 10], [3, 7]) will induce the edges but pairs ([1, 2], [3, 4]) and ([5, 7], [3, 10]) will not. Determine if the resulting graph is a tree or not. Input The first line contains a single integer n (1 ≤ n ≤ 5 ⋅ 10^5) — the number of segments. The i-th of the next n lines contain the description of the i-th segment — two integers l_i and r_i (1 ≤ l_i < r_i ≤ 2n). It is guaranteed that all segments borders are pairwise distinct. Output Print "YES" if the resulting graph is a tree and "NO" otherwise. Examples Input 6 9 12 2 11 1 3 6 10 5 7 4 8 Output YES Input 5 1 3 2 4 5 9 6 8 7 10 Output NO Input 5 5 8 3 6 2 9 7 10 1 4 Output NO Note The graph corresponding to the first example: <image> The graph corresponding to the second example: <image> The graph corresponding to the third example: <image>
instruction
0
70,851
13
141,702
Tags: data structures, dsu, graphs, trees Correct Solution: ``` # -*- coding: utf-8 -*- import sys from heapq import heapify, heappush, heappop def input(): return sys.stdin.readline().strip() def list2d(a, b, c): return [[c] * b for i in range(a)] def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)] def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)] def ceil(x, y=1): return int(-(-x // y)) def INT(): return int(input()) def MAP(): return map(int, input().split()) def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)] def Yes(): print('Yes') def No(): print('No') def YES(): print('YES') def NO(): print('NO') sys.setrecursionlimit(10 ** 9) INF = 10 ** 18 MOD = 10 ** 9 + 7 class UnionFind: def __init__(self, n): self.n = n self.par = [i for i in range(n+1)] self.rank = [0] * (n+1) self.size = [1] * (n+1) self.tree = [True] * (n+1) def find(self, x): if self.par[x] == x: return x else: self.par[x] = self.find(self.par[x]) return self.par[x] def union(self, x, y): x = self.find(x) y = self.find(y) if x == y: self.tree[x] = False return if not self.tree[x] or not self.tree[y]: self.tree[x] = self.tree[y] = False if self.rank[x] < self.rank[y]: self.par[x] = y self.size[y] += self.size[x] else: self.par[y] = x self.size[x] += self.size[y] if self.rank[x] == self.rank[y]: self.rank[x] += 1 def is_same(self, x, y): return self.find(x) == self.find(y) def get_size(self, x=None): if x is not None: return self.size[self.find(x)] else: res = set() for i in range(self.n+1): res.add(self.find(i)) return len(res) - 1 def is_tree(self, x): return self.tree[self.find(x)] N = INT() segs = [0] * (N*2+1) for i in range(N): l, r = MAP() segs[l] = i + 1 segs[r] = -(i + 1) que = [] edges = [] for i, a in enumerate(segs): if a > 0: heappush(que, (-i, a)) else: a = -a tmp = [] while que: j, b = heappop(que) if a == b: break tmp.append((j, b)) edges.append((a, b)) if len(edges) >= N: NO() exit() for j, b in tmp: heappush(que, (j, b)) uf = UnionFind(N) for a, b in edges: uf.union(a, b) if uf.get_size() != 1 or not uf.is_tree(1): NO() else: YES() ```
output
1
70,851
13
141,703
Provide tags and a correct Python 3 solution for this coding contest problem. As the name of the task implies, you are asked to do some work with segments and trees. Recall that a tree is a connected undirected graph such that there is exactly one simple path between every pair of its vertices. You are given n segments [l_1, r_1], [l_2, r_2], ..., [l_n, r_n], l_i < r_i for every i. It is guaranteed that all segments' endpoints are integers, and all endpoints are unique — there is no pair of segments such that they start in the same point, end in the same point or one starts in the same point the other one ends. Let's generate a graph with n vertices from these segments. Vertices v and u are connected by an edge if and only if segments [l_v, r_v] and [l_u, r_u] intersect and neither of it lies fully inside the other one. For example, pairs ([1, 3], [2, 4]) and ([5, 10], [3, 7]) will induce the edges but pairs ([1, 2], [3, 4]) and ([5, 7], [3, 10]) will not. Determine if the resulting graph is a tree or not. Input The first line contains a single integer n (1 ≤ n ≤ 5 ⋅ 10^5) — the number of segments. The i-th of the next n lines contain the description of the i-th segment — two integers l_i and r_i (1 ≤ l_i < r_i ≤ 2n). It is guaranteed that all segments borders are pairwise distinct. Output Print "YES" if the resulting graph is a tree and "NO" otherwise. Examples Input 6 9 12 2 11 1 3 6 10 5 7 4 8 Output YES Input 5 1 3 2 4 5 9 6 8 7 10 Output NO Input 5 5 8 3 6 2 9 7 10 1 4 Output NO Note The graph corresponding to the first example: <image> The graph corresponding to the second example: <image> The graph corresponding to the third example: <image>
instruction
0
70,852
13
141,704
Tags: data structures, dsu, graphs, trees Correct Solution: ``` import sys input = sys.stdin.readline def main(): N = int(input()) LR = [list(map(int, input().split())) for _ in range(N)] A = [None]*(2*N+1) for i, (l, r) in enumerate(LR): A[l] = i A[r] = i graph = [[] for _ in range(N)] num_of_edge = 0 q = [] for n in range(1, 2*N+1): p = A[n] if LR[p][0] == n: q.append(p) else: tmp = [] while True: np = q.pop() if np == p: break else: tmp.append(np) while tmp: np = tmp.pop() q.append(np) num_of_edge += 1 graph[np].append(p) graph[p].append(np) if num_of_edge > N: return False if num_of_edge != N-1: return False q = [0] checked = [False]*N checked[0] = True while q: qq = [] for p in q: for np in graph[p]: if not checked[np]: checked[np] = True qq.append(np) q = qq for p in range(N): if not checked[p]: return False return True if __name__ == "__main__": print("YES" if main() else "NO") ```
output
1
70,852
13
141,705
Provide tags and a correct Python 3 solution for this coding contest problem. As the name of the task implies, you are asked to do some work with segments and trees. Recall that a tree is a connected undirected graph such that there is exactly one simple path between every pair of its vertices. You are given n segments [l_1, r_1], [l_2, r_2], ..., [l_n, r_n], l_i < r_i for every i. It is guaranteed that all segments' endpoints are integers, and all endpoints are unique — there is no pair of segments such that they start in the same point, end in the same point or one starts in the same point the other one ends. Let's generate a graph with n vertices from these segments. Vertices v and u are connected by an edge if and only if segments [l_v, r_v] and [l_u, r_u] intersect and neither of it lies fully inside the other one. For example, pairs ([1, 3], [2, 4]) and ([5, 10], [3, 7]) will induce the edges but pairs ([1, 2], [3, 4]) and ([5, 7], [3, 10]) will not. Determine if the resulting graph is a tree or not. Input The first line contains a single integer n (1 ≤ n ≤ 5 ⋅ 10^5) — the number of segments. The i-th of the next n lines contain the description of the i-th segment — two integers l_i and r_i (1 ≤ l_i < r_i ≤ 2n). It is guaranteed that all segments borders are pairwise distinct. Output Print "YES" if the resulting graph is a tree and "NO" otherwise. Examples Input 6 9 12 2 11 1 3 6 10 5 7 4 8 Output YES Input 5 1 3 2 4 5 9 6 8 7 10 Output NO Input 5 5 8 3 6 2 9 7 10 1 4 Output NO Note The graph corresponding to the first example: <image> The graph corresponding to the second example: <image> The graph corresponding to the third example: <image>
instruction
0
70,853
13
141,706
Tags: data structures, dsu, graphs, trees Correct Solution: ``` import sys class segmTree(): def __init__(self, size=None, array=None): if array is not None: size = len(array) N = 1 while N < size: N <<= 1 self.N = N self.tree = [0] * (2*self.N) if array is not None: for i in range(size): self.tree[i+self.N] = array[i] self.build() def build(self): for i in range(self.N - 1, 0, -1): self.tree[i] = self.tree[i<<1] + self.tree[i<<1|1] def add(self, i, value=1): i += self.N while i > 0: self.tree[i] += value i >>= 1 def findNonzeros(self, l, r): N = self.N l += N r += N cand = [] while l < r: if l & 1: if self.tree[l]: cand.append(l) l += 1 if r & 1: r -= 1 if self.tree[r]: cand.append(r) l >>= 1 r >>= 1 nonzeros = [] while cand: i = cand.pop() if self.tree[i]: if i < N: cand.append(i<<1) cand.append(i<<1|1) else: nonzeros.append(i - N) return nonzeros # inf = open('input.txt', 'r') # reader = (line.rstrip() for line in inf) reader = (line.rstrip() for line in sys.stdin) input = reader.__next__ n = int(input()) segm = [0] * (2 * n + 1) edge = [0] * (2 * n + 1) for i in range(n): l, r = map(int, input().split()) segm[l] = segm[r] = i edge[l] = edge[r] = r # inf.close() opened = segmTree(size=2*n+1) g = [[] for _ in range(n)] ctr = 0 for e in range(1, 2 * n + 1): r = edge[e] if e == r: opened.add(e, -1) else: opened.add(r, 1) for R in opened.findNonzeros(0, r): ctr += 1 if ctr >= n: print('NO') sys.exit() i = segm[r] j = segm[R] g[i].append(j) g[j].append(i) # print(g) visited = [False] * n stack = [0] while stack: v = stack.pop() if not visited[v]: visited[v] = True for to in g[v]: stack.append(to) print('YES' if all(visited) else 'NO') ```
output
1
70,853
13
141,707
Provide tags and a correct Python 3 solution for this coding contest problem. As the name of the task implies, you are asked to do some work with segments and trees. Recall that a tree is a connected undirected graph such that there is exactly one simple path between every pair of its vertices. You are given n segments [l_1, r_1], [l_2, r_2], ..., [l_n, r_n], l_i < r_i for every i. It is guaranteed that all segments' endpoints are integers, and all endpoints are unique — there is no pair of segments such that they start in the same point, end in the same point or one starts in the same point the other one ends. Let's generate a graph with n vertices from these segments. Vertices v and u are connected by an edge if and only if segments [l_v, r_v] and [l_u, r_u] intersect and neither of it lies fully inside the other one. For example, pairs ([1, 3], [2, 4]) and ([5, 10], [3, 7]) will induce the edges but pairs ([1, 2], [3, 4]) and ([5, 7], [3, 10]) will not. Determine if the resulting graph is a tree or not. Input The first line contains a single integer n (1 ≤ n ≤ 5 ⋅ 10^5) — the number of segments. The i-th of the next n lines contain the description of the i-th segment — two integers l_i and r_i (1 ≤ l_i < r_i ≤ 2n). It is guaranteed that all segments borders are pairwise distinct. Output Print "YES" if the resulting graph is a tree and "NO" otherwise. Examples Input 6 9 12 2 11 1 3 6 10 5 7 4 8 Output YES Input 5 1 3 2 4 5 9 6 8 7 10 Output NO Input 5 5 8 3 6 2 9 7 10 1 4 Output NO Note The graph corresponding to the first example: <image> The graph corresponding to the second example: <image> The graph corresponding to the third example: <image>
instruction
0
70,854
13
141,708
Tags: data structures, dsu, graphs, trees Correct Solution: ``` import sys class segmTree(): def __init__(self, size=None, array=None): if array is not None: size = len(array) N = 1 while N < size: N <<= 1 self.N = N self.tree = [0] * (2*self.N) if array is not None: for i in range(size): self.tree[i+self.N] = array[i] self.build() def build(self): for i in range(self.N - 1, 0, -1): self.tree[i] = self.tree[i<<1] + self.tree[i<<1|1] def add(self, i, value=1): i += self.N while i > 0: self.tree[i] += value i >>= 1 def findNonzero(self, l, r): N = self.N l += N r += N cand = [] while l < r: if l & 1: cand.append(l) l += 1 if r & 1: r -= 1 cand.append(r) l >>= 1 r >>= 1 nonzeros = [] while cand: i = cand.pop() if self.tree[i]: if i < N: cand.append(i<<1) cand.append(i<<1|1) else: nonzeros.append(i - N) return nonzeros # inf = open('input.txt', 'r') # reader = (line.rstrip() for line in inf) reader = (line.rstrip() for line in sys.stdin) input = reader.__next__ n = int(input()) segm = [0] * (2 * n + 1) edge = [0] * (2 * n + 1) for i in range(n): l, r = map(int, input().split()) segm[l] = segm[r] = i edge[l] = edge[r] = r # inf.close() opened = segmTree(size=2*n+1) g = [[] for _ in range(n)] ctr = 0 for e in range(1, 2 * n + 1): r = edge[e] if e == r: opened.add(e, -1) else: opened.add(r, 1) for R in opened.findNonzero(0, r): ctr += 1 if ctr >= n: print('NO') sys.exit() i = segm[r] j = segm[R] g[i].append(j) g[j].append(i) # print(g) visited = [False] * n stack = [0] while stack: v = stack.pop() if not visited[v]: visited[v] = True for to in g[v]: stack.append(to) print('YES' if all(visited) else 'NO') ```
output
1
70,854
13
141,709
Provide tags and a correct Python 3 solution for this coding contest problem. As the name of the task implies, you are asked to do some work with segments and trees. Recall that a tree is a connected undirected graph such that there is exactly one simple path between every pair of its vertices. You are given n segments [l_1, r_1], [l_2, r_2], ..., [l_n, r_n], l_i < r_i for every i. It is guaranteed that all segments' endpoints are integers, and all endpoints are unique — there is no pair of segments such that they start in the same point, end in the same point or one starts in the same point the other one ends. Let's generate a graph with n vertices from these segments. Vertices v and u are connected by an edge if and only if segments [l_v, r_v] and [l_u, r_u] intersect and neither of it lies fully inside the other one. For example, pairs ([1, 3], [2, 4]) and ([5, 10], [3, 7]) will induce the edges but pairs ([1, 2], [3, 4]) and ([5, 7], [3, 10]) will not. Determine if the resulting graph is a tree or not. Input The first line contains a single integer n (1 ≤ n ≤ 5 ⋅ 10^5) — the number of segments. The i-th of the next n lines contain the description of the i-th segment — two integers l_i and r_i (1 ≤ l_i < r_i ≤ 2n). It is guaranteed that all segments borders are pairwise distinct. Output Print "YES" if the resulting graph is a tree and "NO" otherwise. Examples Input 6 9 12 2 11 1 3 6 10 5 7 4 8 Output YES Input 5 1 3 2 4 5 9 6 8 7 10 Output NO Input 5 5 8 3 6 2 9 7 10 1 4 Output NO Note The graph corresponding to the first example: <image> The graph corresponding to the second example: <image> The graph corresponding to the third example: <image>
instruction
0
70,855
13
141,710
Tags: data structures, dsu, graphs, trees Correct Solution: ``` import sys reader = (s.rstrip() for s in sys.stdin) input = reader.__next__ class BIT_RSQ(): def __init__(self, n): self.n = n self.data = [0]*(n+2) def add(self, i, v): while i <= self.n: self.data[i] += v i += i & -i def sum(self, i): ret = 0 while(i > 0): ret += self.data[i] i -= i & -i return ret def query(self, l, r): return self.sum(r) - self.sum(l-1) def lowerBound(self, w): if w <= 0: return 0 x, k = 0, 2**self.n.bit_length() while k: if x+k <= self.n and self.data[x+k] < w: w -= self.data[x+k] x += k k >>= 1 return x + 1 n = int(input()) edges = [0]*(2*n) c = [0]*(2*n) BIT = BIT_RSQ(2*n) uf = [-1]*n def root(x): if uf[x] < 0: return x uf[x] = root(uf[x]) return uf[x] def unite(x,y): rx, ry = root(x), root(y) if rx == ry: return False if uf[rx] > uf[ry]: rx, ry = ry, rx uf[rx] += uf[ry] uf[ry] = rx return True for i in range(n): a,b = map(int, input().split()) a,b = a-1,b-1 c[a] = c[b] = i edges[a] = b edges[b] = b for i in reversed(range(2*n)): j = edges[i] if j == i: BIT.add(j+1, 1) else: BIT.add(j+1, -1) cnt = BIT.sum(j+1) while cnt: k = BIT.lowerBound(cnt) if not unite(c[j], c[k-1]): print("NO") exit() cnt -= 1 if sum(i<0 for i in uf) == 1: print("YES") else: print("NO") ```
output
1
70,855
13
141,711
Provide tags and a correct Python 3 solution for this coding contest problem. As the name of the task implies, you are asked to do some work with segments and trees. Recall that a tree is a connected undirected graph such that there is exactly one simple path between every pair of its vertices. You are given n segments [l_1, r_1], [l_2, r_2], ..., [l_n, r_n], l_i < r_i for every i. It is guaranteed that all segments' endpoints are integers, and all endpoints are unique — there is no pair of segments such that they start in the same point, end in the same point or one starts in the same point the other one ends. Let's generate a graph with n vertices from these segments. Vertices v and u are connected by an edge if and only if segments [l_v, r_v] and [l_u, r_u] intersect and neither of it lies fully inside the other one. For example, pairs ([1, 3], [2, 4]) and ([5, 10], [3, 7]) will induce the edges but pairs ([1, 2], [3, 4]) and ([5, 7], [3, 10]) will not. Determine if the resulting graph is a tree or not. Input The first line contains a single integer n (1 ≤ n ≤ 5 ⋅ 10^5) — the number of segments. The i-th of the next n lines contain the description of the i-th segment — two integers l_i and r_i (1 ≤ l_i < r_i ≤ 2n). It is guaranteed that all segments borders are pairwise distinct. Output Print "YES" if the resulting graph is a tree and "NO" otherwise. Examples Input 6 9 12 2 11 1 3 6 10 5 7 4 8 Output YES Input 5 1 3 2 4 5 9 6 8 7 10 Output NO Input 5 5 8 3 6 2 9 7 10 1 4 Output NO Note The graph corresponding to the first example: <image> The graph corresponding to the second example: <image> The graph corresponding to the third example: <image>
instruction
0
70,856
13
141,712
Tags: data structures, dsu, graphs, trees Correct Solution: ``` import sys class segmTree(): def __init__(self, size=None, array=None): if array is not None: size = len(array) N = 1 while N < size: N <<= 1 self.N = N self.tree = [0] * (2*self.N) if array is not None: for i in range(size): self.tree[i+self.N] = array[i] self.build() def build(self): for i in range(self.N - 1, 0, -1): self.tree[i] = self.tree[i<<1] + self.tree[i<<1|1] def add(self, i, value=1): i += self.N while i > 0: self.tree[i] += value i >>= 1 def findNonzeros(self, l, r): N = self.N l += N r += N cand = [] while l < r: if l & 1: if self.tree[l]: cand.append(l) l += 1 if r & 1: r -= 1 if self.tree[r]: cand.append(r) l >>= 1 r >>= 1 ans = [] while cand: i = cand.pop() if i < N: i <<= 1 if self.tree[i]: cand.append(i) if self.tree[i|1]: cand.append(i|1) else: ans.append(i - N) return ans # inf = open('input.txt', 'r') # reader = (line.rstrip() for line in inf) reader = (line.rstrip() for line in sys.stdin) input = reader.__next__ n = int(input()) segm = [0] * (2 * n + 1) edge = [0] * (2 * n + 1) for i in range(n): l, r = map(int, input().split()) segm[l] = segm[r] = i edge[l] = edge[r] = r # inf.close() opened = segmTree(size=2*n+1) g = [[] for _ in range(n)] ctr = 0 for e in range(1, 2 * n + 1): r = edge[e] if e == r: opened.add(e, -1) else: opened.add(r, 1) for R in opened.findNonzeros(0, r): ctr += 1 if ctr >= n: print('NO') sys.exit() i = segm[r] j = segm[R] g[i].append(j) g[j].append(i) # print(g) visited = [False] * n stack = [0] while stack: v = stack.pop() if not visited[v]: visited[v] = True for to in g[v]: stack.append(to) print('YES' if all(visited) else 'NO') ```
output
1
70,856
13
141,713
Provide tags and a correct Python 3 solution for this coding contest problem. As the name of the task implies, you are asked to do some work with segments and trees. Recall that a tree is a connected undirected graph such that there is exactly one simple path between every pair of its vertices. You are given n segments [l_1, r_1], [l_2, r_2], ..., [l_n, r_n], l_i < r_i for every i. It is guaranteed that all segments' endpoints are integers, and all endpoints are unique — there is no pair of segments such that they start in the same point, end in the same point or one starts in the same point the other one ends. Let's generate a graph with n vertices from these segments. Vertices v and u are connected by an edge if and only if segments [l_v, r_v] and [l_u, r_u] intersect and neither of it lies fully inside the other one. For example, pairs ([1, 3], [2, 4]) and ([5, 10], [3, 7]) will induce the edges but pairs ([1, 2], [3, 4]) and ([5, 7], [3, 10]) will not. Determine if the resulting graph is a tree or not. Input The first line contains a single integer n (1 ≤ n ≤ 5 ⋅ 10^5) — the number of segments. The i-th of the next n lines contain the description of the i-th segment — two integers l_i and r_i (1 ≤ l_i < r_i ≤ 2n). It is guaranteed that all segments borders are pairwise distinct. Output Print "YES" if the resulting graph is a tree and "NO" otherwise. Examples Input 6 9 12 2 11 1 3 6 10 5 7 4 8 Output YES Input 5 1 3 2 4 5 9 6 8 7 10 Output NO Input 5 5 8 3 6 2 9 7 10 1 4 Output NO Note The graph corresponding to the first example: <image> The graph corresponding to the second example: <image> The graph corresponding to the third example: <image>
instruction
0
70,857
13
141,714
Tags: data structures, dsu, graphs, trees Correct Solution: ``` import sys from array import array # noqa: F401 from typing import Dict, List, Tuple, TypeVar, Generic, Sequence, Union # noqa: F401 def input(): return sys.stdin.buffer.readline().decode('utf-8') class UnionFind(object): __slots__ = ['nodes'] def __init__(self, n: int): self.nodes = [-1] * n def size(self, x: int) -> int: return -self.nodes[self.find(x)] def find(self, x: int) -> int: if self.nodes[x] < 0: return x else: self.nodes[x] = self.find(self.nodes[x]) return self.nodes[x] def unite(self, x: int, y: int) -> bool: root_x, root_y, nodes = self.find(x), self.find(y), self.nodes if root_x != root_y: if nodes[root_x] > nodes[root_y]: root_x, root_y = root_y, root_x nodes[root_x] += nodes[root_y] nodes[root_y] = root_x return root_x != root_y def main(): from heapq import heappush, heappop n = int(input()) seg_l, seg_r = [0] * n, [0] * n for i, (l, r) in enumerate(map(int, input().split()) for _ in range(n)): seg_l[i] = l seg_r[i] = r order = sorted(range(n), key=lambda i: seg_l[i]) hq: List[Tuple[int, int]] = [] edge_cnt = 0 uf = UnionFind(n) for i in order: while hq and hq[0][0] < seg_l[i]: heappop(hq) tmp = [] while hq and hq[0][0] < seg_r[i]: uf.unite(i, hq[0][1]) edge_cnt += 1 tmp.append(heappop(hq)) if edge_cnt >= n: print('NO') exit() while tmp: heappush(hq, tmp.pop()) heappush(hq, (seg_r[i], i)) if edge_cnt == n - 1 and uf.size(0) == n: print('YES') else: print('NO') if __name__ == '__main__': main() ```
output
1
70,857
13
141,715
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. As the name of the task implies, you are asked to do some work with segments and trees. Recall that a tree is a connected undirected graph such that there is exactly one simple path between every pair of its vertices. You are given n segments [l_1, r_1], [l_2, r_2], ..., [l_n, r_n], l_i < r_i for every i. It is guaranteed that all segments' endpoints are integers, and all endpoints are unique — there is no pair of segments such that they start in the same point, end in the same point or one starts in the same point the other one ends. Let's generate a graph with n vertices from these segments. Vertices v and u are connected by an edge if and only if segments [l_v, r_v] and [l_u, r_u] intersect and neither of it lies fully inside the other one. For example, pairs ([1, 3], [2, 4]) and ([5, 10], [3, 7]) will induce the edges but pairs ([1, 2], [3, 4]) and ([5, 7], [3, 10]) will not. Determine if the resulting graph is a tree or not. Input The first line contains a single integer n (1 ≤ n ≤ 5 ⋅ 10^5) — the number of segments. The i-th of the next n lines contain the description of the i-th segment — two integers l_i and r_i (1 ≤ l_i < r_i ≤ 2n). It is guaranteed that all segments borders are pairwise distinct. Output Print "YES" if the resulting graph is a tree and "NO" otherwise. Examples Input 6 9 12 2 11 1 3 6 10 5 7 4 8 Output YES Input 5 1 3 2 4 5 9 6 8 7 10 Output NO Input 5 5 8 3 6 2 9 7 10 1 4 Output NO Note The graph corresponding to the first example: <image> The graph corresponding to the second example: <image> The graph corresponding to the third example: <image> Submitted Solution: ``` # 1278D - Segment Tree class DSU: def __init__(self, arr): self.hash = {} for (l, _) in arr: self.hash[l] = {l: True} def same_set(self, a, b): return b in self.hash[a] def union(self, a, b): if len(self.hash[a]) > len(self.hash[b]): self.hash[a][b] = True self.hash[b] = self.hash[a] else: self.hash[b][a] = True self.hash[a] = self.hash[b] if __name__ == "__main__": n = int(input()) arr = [] for i in range(n): inp = input().rstrip().split(" ") arr.append((int(inp[0]), int(inp[1]))) arr.sort(key=lambda tup: tup[0]) dsu = DSU(arr) root = arr[0] nodes = [[root, 0]] tree = True while len(nodes) > 0: node, index = nodes.pop() index += 1 while index < len(arr): neighbor = arr[index] if neighbor[0] > node[1]: break elif neighbor[1] > node[1]: # add edge if dsu.same_set(node[0], neighbor[0]): tree = False break else: dsu.union(node[0], neighbor[0]) nodes.append([neighbor, index]) else: pass index += 1 if tree and len(dsu.hash[root[0]]) == n: print("YES") else: print("NO") ```
instruction
0
70,858
13
141,716
No
output
1
70,858
13
141,717
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. As the name of the task implies, you are asked to do some work with segments and trees. Recall that a tree is a connected undirected graph such that there is exactly one simple path between every pair of its vertices. You are given n segments [l_1, r_1], [l_2, r_2], ..., [l_n, r_n], l_i < r_i for every i. It is guaranteed that all segments' endpoints are integers, and all endpoints are unique — there is no pair of segments such that they start in the same point, end in the same point or one starts in the same point the other one ends. Let's generate a graph with n vertices from these segments. Vertices v and u are connected by an edge if and only if segments [l_v, r_v] and [l_u, r_u] intersect and neither of it lies fully inside the other one. For example, pairs ([1, 3], [2, 4]) and ([5, 10], [3, 7]) will induce the edges but pairs ([1, 2], [3, 4]) and ([5, 7], [3, 10]) will not. Determine if the resulting graph is a tree or not. Input The first line contains a single integer n (1 ≤ n ≤ 5 ⋅ 10^5) — the number of segments. The i-th of the next n lines contain the description of the i-th segment — two integers l_i and r_i (1 ≤ l_i < r_i ≤ 2n). It is guaranteed that all segments borders are pairwise distinct. Output Print "YES" if the resulting graph is a tree and "NO" otherwise. Examples Input 6 9 12 2 11 1 3 6 10 5 7 4 8 Output YES Input 5 1 3 2 4 5 9 6 8 7 10 Output NO Input 5 5 8 3 6 2 9 7 10 1 4 Output NO Note The graph corresponding to the first example: <image> The graph corresponding to the second example: <image> The graph corresponding to the third example: <image> Submitted Solution: ``` import random x = random.randint(0,1) if x == 0: print('NO') else: print('YES')############## ```
instruction
0
70,859
13
141,718
No
output
1
70,859
13
141,719
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. As the name of the task implies, you are asked to do some work with segments and trees. Recall that a tree is a connected undirected graph such that there is exactly one simple path between every pair of its vertices. You are given n segments [l_1, r_1], [l_2, r_2], ..., [l_n, r_n], l_i < r_i for every i. It is guaranteed that all segments' endpoints are integers, and all endpoints are unique — there is no pair of segments such that they start in the same point, end in the same point or one starts in the same point the other one ends. Let's generate a graph with n vertices from these segments. Vertices v and u are connected by an edge if and only if segments [l_v, r_v] and [l_u, r_u] intersect and neither of it lies fully inside the other one. For example, pairs ([1, 3], [2, 4]) and ([5, 10], [3, 7]) will induce the edges but pairs ([1, 2], [3, 4]) and ([5, 7], [3, 10]) will not. Determine if the resulting graph is a tree or not. Input The first line contains a single integer n (1 ≤ n ≤ 5 ⋅ 10^5) — the number of segments. The i-th of the next n lines contain the description of the i-th segment — two integers l_i and r_i (1 ≤ l_i < r_i ≤ 2n). It is guaranteed that all segments borders are pairwise distinct. Output Print "YES" if the resulting graph is a tree and "NO" otherwise. Examples Input 6 9 12 2 11 1 3 6 10 5 7 4 8 Output YES Input 5 1 3 2 4 5 9 6 8 7 10 Output NO Input 5 5 8 3 6 2 9 7 10 1 4 Output NO Note The graph corresponding to the first example: <image> The graph corresponding to the second example: <image> The graph corresponding to the third example: <image> Submitted Solution: ``` import random x = random.randint(0,1) if x == 0: print('NO') else: print('YES')# ```
instruction
0
70,860
13
141,720
No
output
1
70,860
13
141,721
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. As the name of the task implies, you are asked to do some work with segments and trees. Recall that a tree is a connected undirected graph such that there is exactly one simple path between every pair of its vertices. You are given n segments [l_1, r_1], [l_2, r_2], ..., [l_n, r_n], l_i < r_i for every i. It is guaranteed that all segments' endpoints are integers, and all endpoints are unique — there is no pair of segments such that they start in the same point, end in the same point or one starts in the same point the other one ends. Let's generate a graph with n vertices from these segments. Vertices v and u are connected by an edge if and only if segments [l_v, r_v] and [l_u, r_u] intersect and neither of it lies fully inside the other one. For example, pairs ([1, 3], [2, 4]) and ([5, 10], [3, 7]) will induce the edges but pairs ([1, 2], [3, 4]) and ([5, 7], [3, 10]) will not. Determine if the resulting graph is a tree or not. Input The first line contains a single integer n (1 ≤ n ≤ 5 ⋅ 10^5) — the number of segments. The i-th of the next n lines contain the description of the i-th segment — two integers l_i and r_i (1 ≤ l_i < r_i ≤ 2n). It is guaranteed that all segments borders are pairwise distinct. Output Print "YES" if the resulting graph is a tree and "NO" otherwise. Examples Input 6 9 12 2 11 1 3 6 10 5 7 4 8 Output YES Input 5 1 3 2 4 5 9 6 8 7 10 Output NO Input 5 5 8 3 6 2 9 7 10 1 4 Output NO Note The graph corresponding to the first example: <image> The graph corresponding to the second example: <image> The graph corresponding to the third example: <image> Submitted Solution: ``` # from debug import debug import math n = int(input()) inf = int(1e6) g = 0 ls = [-1 for i in range(inf)] rs = [-1 for i in range(inf)] q = [] for i in range(n): l, r = map(int, input().split()) ls[l-1] = i rs[r-1] = i # print(" |"*(l-1)+"_|"*(r-l+1)+" |"*(15-r)) graph = [[] for i in range(n)] # print(ls) # print(rs) q = [] e = 0 for i in range(inf): # print(1, q) if ls[i] != -1: q.append(ls[i]) # print(2, q) elif rs[i] != -1: index = q.index(rs[i]) for j in range(index+1, len(q)): graph[q[j]].append(rs[i]) graph[rs[i]].append(q[j]) e+=1 q.remove(rs[i]) # print(3, q) else: break def dfs(n): v[n] = 1 for i in graph[n]: if not v[i]: dfs(i) if e == n: print("NO") else: v = [0 for i in range(n)] for i in range(n): if len(graph[i]) == 0: v[i] = 1 dfs(0) if all(v) == 1: print("YES") else: print("NO") ```
instruction
0
70,861
13
141,722
No
output
1
70,861
13
141,723
Provide tags and a correct Python 3 solution for this coding contest problem. Dasha decided to have a rest after solving the problem. She had been ready to start her favourite activity — origami, but remembered the puzzle that she could not solve. <image> The tree is a non-oriented connected graph without cycles. In particular, there always are n - 1 edges in a tree with n vertices. The puzzle is to position the vertices at the points of the Cartesian plane with integral coordinates, so that the segments between the vertices connected by edges are parallel to the coordinate axes. Also, the intersection of segments is allowed only at their ends. Distinct vertices should be placed at different points. Help Dasha to find any suitable way to position the tree vertices on the plane. It is guaranteed that if it is possible to position the tree vertices on the plane without violating the condition which is given above, then you can do it by using points with integral coordinates which don't exceed 1018 in absolute value. Input The first line contains single integer n (1 ≤ n ≤ 30) — the number of vertices in the tree. Each of next n - 1 lines contains two integers ui, vi (1 ≤ ui, vi ≤ n) that mean that the i-th edge of the tree connects vertices ui and vi. It is guaranteed that the described graph is a tree. Output If the puzzle doesn't have a solution then in the only line print "NO". Otherwise, the first line should contain "YES". The next n lines should contain the pair of integers xi, yi (|xi|, |yi| ≤ 1018) — the coordinates of the point which corresponds to the i-th vertex of the tree. If there are several solutions, print any of them. Examples Input 7 1 2 1 3 2 4 2 5 3 6 3 7 Output YES 0 0 1 0 0 1 2 0 1 -1 -1 1 0 2 Input 6 1 2 2 3 2 4 2 5 2 6 Output NO Input 4 1 2 2 3 3 4 Output YES 3 3 4 3 5 3 6 3 Note In the first sample one of the possible positions of tree is: <image>
instruction
0
71,264
13
142,528
Tags: constructive algorithms, dfs and similar, graphs, greedy, trees Correct Solution: ``` # ---------------------------iye ha aam zindegi--------------------------------------------- import math import random import heapq, bisect import sys from collections import deque, defaultdict from fractions import Fraction import sys #import threading from collections import defaultdict #threading.stack_size(10**8) mod = 10 ** 9 + 7 mod1 = 998244353 # ------------------------------warmup---------------------------- import os import sys from io import BytesIO, IOBase #sys.setrecursionlimit(300000) BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # -------------------game starts now----------------------------------------------------import math class TreeNode: def __init__(self, k, v): self.key = k self.value = v self.left = None self.right = None self.parent = None self.height = 1 self.num_left = 1 self.num_total = 1 class AvlTree: def __init__(self): self._tree = None def add(self, k, v): if not self._tree: self._tree = TreeNode(k, v) return node = self._add(k, v) if node: self._rebalance(node) def _add(self, k, v): node = self._tree while node: if k < node.key: if node.left: node = node.left else: node.left = TreeNode(k, v) node.left.parent = node return node.left elif node.key < k: if node.right: node = node.right else: node.right = TreeNode(k, v) node.right.parent = node return node.right else: node.value = v return @staticmethod def get_height(x): return x.height if x else 0 @staticmethod def get_num_total(x): return x.num_total if x else 0 def _rebalance(self, node): n = node while n: lh = self.get_height(n.left) rh = self.get_height(n.right) n.height = max(lh, rh) + 1 balance_factor = lh - rh n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right) n.num_left = 1 + self.get_num_total(n.left) if balance_factor > 1: if self.get_height(n.left.left) < self.get_height(n.left.right): self._rotate_left(n.left) self._rotate_right(n) elif balance_factor < -1: if self.get_height(n.right.right) < self.get_height(n.right.left): self._rotate_right(n.right) self._rotate_left(n) else: n = n.parent def _remove_one(self, node): """ Side effect!!! Changes node. Node should have exactly one child """ replacement = node.left or node.right if node.parent: if AvlTree._is_left(node): node.parent.left = replacement else: node.parent.right = replacement replacement.parent = node.parent node.parent = None else: self._tree = replacement replacement.parent = None node.left = None node.right = None node.parent = None self._rebalance(replacement) def _remove_leaf(self, node): if node.parent: if AvlTree._is_left(node): node.parent.left = None else: node.parent.right = None self._rebalance(node.parent) else: self._tree = None node.parent = None node.left = None node.right = None def remove(self, k): node = self._get_node(k) if not node: return if AvlTree._is_leaf(node): self._remove_leaf(node) return if node.left and node.right: nxt = AvlTree._get_next(node) node.key = nxt.key node.value = nxt.value if self._is_leaf(nxt): self._remove_leaf(nxt) else: self._remove_one(nxt) self._rebalance(node) else: self._remove_one(node) def get(self, k): node = self._get_node(k) return node.value if node else -1 def _get_node(self, k): if not self._tree: return None node = self._tree while node: if k < node.key: node = node.left elif node.key < k: node = node.right else: return node return None def get_at(self, pos): x = pos + 1 node = self._tree while node: if x < node.num_left: node = node.left elif node.num_left < x: x -= node.num_left node = node.right else: return (node.key, node.value) raise IndexError("Out of ranges") @staticmethod def _is_left(node): return node.parent.left and node.parent.left == node @staticmethod def _is_leaf(node): return node.left is None and node.right is None def _rotate_right(self, node): if not node.parent: self._tree = node.left node.left.parent = None elif AvlTree._is_left(node): node.parent.left = node.left node.left.parent = node.parent else: node.parent.right = node.left node.left.parent = node.parent bk = node.left.right node.left.right = node node.parent = node.left node.left = bk if bk: bk.parent = node node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1 node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right) node.num_left = 1 + self.get_num_total(node.left) def _rotate_left(self, node): if not node.parent: self._tree = node.right node.right.parent = None elif AvlTree._is_left(node): node.parent.left = node.right node.right.parent = node.parent else: node.parent.right = node.right node.right.parent = node.parent bk = node.right.left node.right.left = node node.parent = node.right node.right = bk if bk: bk.parent = node node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1 node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right) node.num_left = 1 + self.get_num_total(node.left) @staticmethod def _get_next(node): if not node.right: return node.parent n = node.right while n.left: n = n.left return n # -----------------------------------------------binary seacrh tree--------------------------------------- class SegmentTree1: def __init__(self, data, default=300006, func=lambda a, b: min(a , b)): """initialize the segment tree with data""" self._default = default self._func = func self._len = len(data) self._size = _size = 1 << (self._len - 1).bit_length() self.data = [default] * (2 * _size) self.data[_size:_size + self._len] = data for i in reversed(range(_size)): self.data[i] = func(self.data[i + i], self.data[i + i + 1]) def __delitem__(self, idx): self[idx] = self._default def __getitem__(self, idx): return self.data[idx + self._size] def __setitem__(self, idx, value): idx += self._size self.data[idx] = value idx >>= 1 while idx: self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) idx >>= 1 def __len__(self): return self._len def query(self, start, stop): if start == stop: return self.__getitem__(start) stop += 1 start += self._size stop += self._size res = self._default while start < stop: if start & 1: res = self._func(res, self.data[start]) start += 1 if stop & 1: stop -= 1 res = self._func(res, self.data[stop]) start >>= 1 stop >>= 1 return res def __repr__(self): return "SegmentTree({0})".format(self.data) # -------------------game starts now----------------------------------------------------import math class SegmentTree: def __init__(self, data, default=0, func=lambda a, b:a + b): """initialize the segment tree with data""" self._default = default self._func = func self._len = len(data) self._size = _size = 1 << (self._len - 1).bit_length() self.data = [default] * (2 * _size) self.data[_size:_size + self._len] = data for i in reversed(range(_size)): self.data[i] = func(self.data[i + i], self.data[i + i + 1]) def __delitem__(self, idx): self[idx] = self._default def __getitem__(self, idx): return self.data[idx + self._size] def __setitem__(self, idx, value): idx += self._size self.data[idx] = value idx >>= 1 while idx: self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) idx >>= 1 def __len__(self): return self._len def query(self, start, stop): if start == stop: return self.__getitem__(start) stop += 1 start += self._size stop += self._size res = self._default while start < stop: if start & 1: res = self._func(res, self.data[start]) start += 1 if stop & 1: stop -= 1 res = self._func(res, self.data[stop]) start >>= 1 stop >>= 1 return res def __repr__(self): return "SegmentTree({0})".format(self.data) # -------------------------------iye ha chutiya zindegi------------------------------------- class Factorial: def __init__(self, MOD): self.MOD = MOD self.factorials = [1, 1] self.invModulos = [0, 1] self.invFactorial_ = [1, 1] def calc(self, n): if n <= -1: print("Invalid argument to calculate n!") print("n must be non-negative value. But the argument was " + str(n)) exit() if n < len(self.factorials): return self.factorials[n] nextArr = [0] * (n + 1 - len(self.factorials)) initialI = len(self.factorials) prev = self.factorials[-1] m = self.MOD for i in range(initialI, n + 1): prev = nextArr[i - initialI] = prev * i % m self.factorials += nextArr return self.factorials[n] def inv(self, n): if n <= -1: print("Invalid argument to calculate n^(-1)") print("n must be non-negative value. But the argument was " + str(n)) exit() p = self.MOD pi = n % p if pi < len(self.invModulos): return self.invModulos[pi] nextArr = [0] * (n + 1 - len(self.invModulos)) initialI = len(self.invModulos) for i in range(initialI, min(p, n + 1)): next = -self.invModulos[p % i] * (p // i) % p self.invModulos.append(next) return self.invModulos[pi] def invFactorial(self, n): if n <= -1: print("Invalid argument to calculate (n^(-1))!") print("n must be non-negative value. But the argument was " + str(n)) exit() if n < len(self.invFactorial_): return self.invFactorial_[n] self.inv(n) # To make sure already calculated n^-1 nextArr = [0] * (n + 1 - len(self.invFactorial_)) initialI = len(self.invFactorial_) prev = self.invFactorial_[-1] p = self.MOD for i in range(initialI, n + 1): prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p self.invFactorial_ += nextArr return self.invFactorial_[n] class Combination: def __init__(self, MOD): self.MOD = MOD self.factorial = Factorial(MOD) def ncr(self, n, k): if k < 0 or n < k: return 0 k = min(k, n - k) f = self.factorial return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD # --------------------------------------iye ha combinations ka zindegi--------------------------------- def powm(a, n, m): if a == 1 or n == 0: return 1 if n % 2 == 0: s = powm(a, n // 2, m) return s * s % m else: return a * powm(a, n - 1, m) % m # --------------------------------------iye ha power ka zindegi--------------------------------- def sort_list(list1, list2): zipped_pairs = zip(list2, list1) z = [x for _, x in sorted(zipped_pairs)] return z # --------------------------------------------------product---------------------------------------- def product(l): por = 1 for i in range(len(l)): por *= l[i] return por # --------------------------------------------------binary---------------------------------------- def binarySearchCount(arr, n, key): left = 0 right = n - 1 count = 0 while (left <= right): mid = int((right + left) / 2) # Check if middle element is # less than or equal to key if (arr[mid] <key): count = mid + 1 left = mid + 1 # If key is smaller, ignore right half else: right = mid - 1 return count # --------------------------------------------------binary---------------------------------------- def countdig(n): c = 0 while (n > 0): n //= 10 c += 1 return c def binary(x, length): y = bin(x)[2:] return y if len(y) >= length else "0" * (length - len(y)) + y def countGreater(arr, n, k): l = 0 r = n - 1 # Stores the index of the left most element # from the array which is greater than k leftGreater = n # Finds number of elements greater than k while (l <= r): m = int(l + (r - l) / 2) if (arr[m] >= k): leftGreater = m r = m - 1 # If mid element is less than # or equal to k update l else: l = m + 1 # Return the count of elements # greater than k return (n - leftGreater) # --------------------------------------------------binary------------------------------------ class TrieNode: def __init__(self): self.children = [None] * 26 self.isEndOfWord = False class Trie: def __init__(self): self.root = self.getNode() def getNode(self): return TrieNode() def _charToIndex(self, ch): return ord(ch) - ord('a') def insert(self, key): pCrawl = self.root length = len(key) for level in range(length): index = self._charToIndex(key[level]) if not pCrawl.children[index]: pCrawl.children[index] = self.getNode() pCrawl = pCrawl.children[index] pCrawl.isEndOfWord = True def search(self, key): pCrawl = self.root length = len(key) for level in range(length): index = self._charToIndex(key[level]) if not pCrawl.children[index]: return False pCrawl = pCrawl.children[index] return pCrawl != None and pCrawl.isEndOfWord #-----------------------------------------trie--------------------------------- class Node: def __init__(self, data): self.data = data self.height=0 self.left = None # left node for 0 self.right = None # right node for 1 class BinaryTrie: def __init__(self): self.root = Node(0) def insert(self, pre_xor): self.temp = self.root for i in range(31, -1, -1): val = pre_xor & (1 << i) if val==0: if not self.temp.right: self.temp.right = Node(0) self.temp = self.temp.right elif val>=1: if not self.temp.left: self.temp.left = Node(0) self.temp = self.temp.left def do(self,temp): if not temp: return 0 ter=temp temp.height=self.do(ter.left)+self.do(ter.right) if temp.height==0: temp.height+=1 return temp.height def query(self, xor): self.temp = self.root cur=0 i=31 while(i>-1): val = xor & (1 << i) if not self.temp: return cur if val>=1: self.opp = self.temp.right if self.temp.left: self.temp = self.temp.left else: return cur else: self.opp=self.temp.left if self.temp.right: self.temp = self.temp.right else: return cur if self.temp.height==pow(2,i): cur+=1<<(i) self.temp=self.opp i-=1 return cur #-------------------------bin trie------------------------------------------- n=int(input()) if n==1: print("YES") print(0,0) sys.exit(0) ans=[(0,0) for i in range(n)] done=set() def dfs(v,a,b,d,p,rem): ans[v]=(a,b) t=0 rem=((-1)*rem[0],(-1)*rem[1]) w=[(1,0),(0,1),(-1,0),(0,-1),(0,0)] w.remove(rem) for i in graph[v]: if i==p: continue dfs(i,a+d*w[t][0],b+d*w[t][1],d//2,v,w[t]) t+=1 graph=defaultdict(list) d=defaultdict(int) for i in range(n-1): x,y=map(int,input().split()) d[x-1]+=1 d[y-1]+=1 graph[x-1].append(y-1) graph[y-1].append(x-1) if max(d.values())>4: print("NO") else: dfs(0,0,0,2**58,-1,(0,0)) print("YES") for i in range(n): print(*ans[i]) ```
output
1
71,264
13
142,529
Provide tags and a correct Python 3 solution for this coding contest problem. Dasha decided to have a rest after solving the problem. She had been ready to start her favourite activity — origami, but remembered the puzzle that she could not solve. <image> The tree is a non-oriented connected graph without cycles. In particular, there always are n - 1 edges in a tree with n vertices. The puzzle is to position the vertices at the points of the Cartesian plane with integral coordinates, so that the segments between the vertices connected by edges are parallel to the coordinate axes. Also, the intersection of segments is allowed only at their ends. Distinct vertices should be placed at different points. Help Dasha to find any suitable way to position the tree vertices on the plane. It is guaranteed that if it is possible to position the tree vertices on the plane without violating the condition which is given above, then you can do it by using points with integral coordinates which don't exceed 1018 in absolute value. Input The first line contains single integer n (1 ≤ n ≤ 30) — the number of vertices in the tree. Each of next n - 1 lines contains two integers ui, vi (1 ≤ ui, vi ≤ n) that mean that the i-th edge of the tree connects vertices ui and vi. It is guaranteed that the described graph is a tree. Output If the puzzle doesn't have a solution then in the only line print "NO". Otherwise, the first line should contain "YES". The next n lines should contain the pair of integers xi, yi (|xi|, |yi| ≤ 1018) — the coordinates of the point which corresponds to the i-th vertex of the tree. If there are several solutions, print any of them. Examples Input 7 1 2 1 3 2 4 2 5 3 6 3 7 Output YES 0 0 1 0 0 1 2 0 1 -1 -1 1 0 2 Input 6 1 2 2 3 2 4 2 5 2 6 Output NO Input 4 1 2 2 3 3 4 Output YES 3 3 4 3 5 3 6 3 Note In the first sample one of the possible positions of tree is: <image>
instruction
0
71,265
13
142,530
Tags: constructive algorithms, dfs and similar, graphs, greedy, trees Correct Solution: ``` def main(): n = int(input()) graph = [[] for i in range(n)] ans = [(0,0)] * n for _ in range(n - 1): u, v = [int(el) for el in input().split()] u -= 1 v -= 1 graph[u].append(v) graph[v].append(u) for l in graph: if len(l) > 4: print('NO') return step = 1 << 28 used = [False] * n def dfs(v, direction, step, koord): used[v] = True if direction == 'u': my_koord = (koord[0] + step, koord[1]) dirs = ['u', 'l', 'r'] elif direction == 'd': my_koord = (koord[0] - step, koord[1]) dirs = ['d', 'l', 'r'] elif direction == 'l': my_koord = (koord[0], koord[1] - step) dirs = ['u', 'd', 'l'] elif direction == 'r': my_koord = (koord[0], koord[1] + step) dirs = ['u', 'd', 'r'] elif direction == '': my_koord = (0, 0) dirs = ['u', 'd', 'l', 'r'] ans[v] = my_koord d = 0 for u in graph[v]: if not used[u]: dfs(u, dirs[d], step >> 1, my_koord) d += 1 dfs(0, '', step, (0, 0)) print('YES') for k in ans: print(k[0], k[1]) main() ```
output
1
71,265
13
142,531
Provide tags and a correct Python 3 solution for this coding contest problem. Dasha decided to have a rest after solving the problem. She had been ready to start her favourite activity — origami, but remembered the puzzle that she could not solve. <image> The tree is a non-oriented connected graph without cycles. In particular, there always are n - 1 edges in a tree with n vertices. The puzzle is to position the vertices at the points of the Cartesian plane with integral coordinates, so that the segments between the vertices connected by edges are parallel to the coordinate axes. Also, the intersection of segments is allowed only at their ends. Distinct vertices should be placed at different points. Help Dasha to find any suitable way to position the tree vertices on the plane. It is guaranteed that if it is possible to position the tree vertices on the plane without violating the condition which is given above, then you can do it by using points with integral coordinates which don't exceed 1018 in absolute value. Input The first line contains single integer n (1 ≤ n ≤ 30) — the number of vertices in the tree. Each of next n - 1 lines contains two integers ui, vi (1 ≤ ui, vi ≤ n) that mean that the i-th edge of the tree connects vertices ui and vi. It is guaranteed that the described graph is a tree. Output If the puzzle doesn't have a solution then in the only line print "NO". Otherwise, the first line should contain "YES". The next n lines should contain the pair of integers xi, yi (|xi|, |yi| ≤ 1018) — the coordinates of the point which corresponds to the i-th vertex of the tree. If there are several solutions, print any of them. Examples Input 7 1 2 1 3 2 4 2 5 3 6 3 7 Output YES 0 0 1 0 0 1 2 0 1 -1 -1 1 0 2 Input 6 1 2 2 3 2 4 2 5 2 6 Output NO Input 4 1 2 2 3 3 4 Output YES 3 3 4 3 5 3 6 3 Note In the first sample one of the possible positions of tree is: <image>
instruction
0
71,266
13
142,532
Tags: constructive algorithms, dfs and similar, graphs, greedy, trees Correct Solution: ``` #!/usr/bin/env python3 from collections import * def ri(): return map(int, input().split()) d = [[1,0], [0, 1], [-1, 0], [0, -1]] def bfs(s, adj, v, l): if v[s] == 1: return 0 q = deque() q.append(s) v[s] = 1 while q: n = q.popleft() for a in adj[n]: if v[a] == 0: for i in range(4): if dv[n][i] == 0: dv[n][i] = 1 break pos[a][0] = pos[n][0] + d[i][0]*2**(31-l[n]) pos[a][1] = pos[n][1] + d[i][1]*2**(31-l[n]) if i == 0: dv[a][2] = 1 elif i == 1: dv[a][3] = 1 elif i == 2: dv[a][0] = 1 elif i == 3: dv[a][1] = 1 l[a] = l[n] + 1 q.append(a) v[a] = 1 n = int(input()) adj = [set() for i in range(n)] v = [0 for i in range(n)] l = [0 for i in range(n)] dv = [[0,0,0,0] for i in range(n)] pos = [[0, 0] for i in range(n)] for i in range(n-1): a, b = ri() a -= 1 b -= 1 adj[a].add(b) adj[b].add(a) for i in range(n): if len(adj[i]) > 4: print("NO") exit() bfs(0, adj, v, l) print("YES") for i in range(n): print(pos[i][0], pos[i][1]) ```
output
1
71,266
13
142,533
Provide tags and a correct Python 3 solution for this coding contest problem. Dasha decided to have a rest after solving the problem. She had been ready to start her favourite activity — origami, but remembered the puzzle that she could not solve. <image> The tree is a non-oriented connected graph without cycles. In particular, there always are n - 1 edges in a tree with n vertices. The puzzle is to position the vertices at the points of the Cartesian plane with integral coordinates, so that the segments between the vertices connected by edges are parallel to the coordinate axes. Also, the intersection of segments is allowed only at their ends. Distinct vertices should be placed at different points. Help Dasha to find any suitable way to position the tree vertices on the plane. It is guaranteed that if it is possible to position the tree vertices on the plane without violating the condition which is given above, then you can do it by using points with integral coordinates which don't exceed 1018 in absolute value. Input The first line contains single integer n (1 ≤ n ≤ 30) — the number of vertices in the tree. Each of next n - 1 lines contains two integers ui, vi (1 ≤ ui, vi ≤ n) that mean that the i-th edge of the tree connects vertices ui and vi. It is guaranteed that the described graph is a tree. Output If the puzzle doesn't have a solution then in the only line print "NO". Otherwise, the first line should contain "YES". The next n lines should contain the pair of integers xi, yi (|xi|, |yi| ≤ 1018) — the coordinates of the point which corresponds to the i-th vertex of the tree. If there are several solutions, print any of them. Examples Input 7 1 2 1 3 2 4 2 5 3 6 3 7 Output YES 0 0 1 0 0 1 2 0 1 -1 -1 1 0 2 Input 6 1 2 2 3 2 4 2 5 2 6 Output NO Input 4 1 2 2 3 3 4 Output YES 3 3 4 3 5 3 6 3 Note In the first sample one of the possible positions of tree is: <image>
instruction
0
71,267
13
142,534
Tags: constructive algorithms, dfs and similar, graphs, greedy, trees Correct Solution: ``` n = int(input()) p = [set() for i in range(n)] for k in range(n - 1): u, v = map(int, input().split()) p[u - 1].add(v - 1) p[v - 1].add(u - 1) s = [(0, 0)] * n t = [(0, 1 << 30, 7)] l = [1, 0, -1, 0, 1] while t: u, d, j = t.pop() x, y = s[u] i = 0 for v in p[u]: if i == j: i += 1 if i > 3: exit(print('NO')) p[v].remove(u) s[v] = (x + l[i] * d, y + l[i + 1] * d) t.append((v, d >> 1, (i + 2) % 4)) i += 1 print('YES') for x, y in s: print(x, y) ```
output
1
71,267
13
142,535
Provide tags and a correct Python 3 solution for this coding contest problem. Dasha decided to have a rest after solving the problem. She had been ready to start her favourite activity — origami, but remembered the puzzle that she could not solve. <image> The tree is a non-oriented connected graph without cycles. In particular, there always are n - 1 edges in a tree with n vertices. The puzzle is to position the vertices at the points of the Cartesian plane with integral coordinates, so that the segments between the vertices connected by edges are parallel to the coordinate axes. Also, the intersection of segments is allowed only at their ends. Distinct vertices should be placed at different points. Help Dasha to find any suitable way to position the tree vertices on the plane. It is guaranteed that if it is possible to position the tree vertices on the plane without violating the condition which is given above, then you can do it by using points with integral coordinates which don't exceed 1018 in absolute value. Input The first line contains single integer n (1 ≤ n ≤ 30) — the number of vertices in the tree. Each of next n - 1 lines contains two integers ui, vi (1 ≤ ui, vi ≤ n) that mean that the i-th edge of the tree connects vertices ui and vi. It is guaranteed that the described graph is a tree. Output If the puzzle doesn't have a solution then in the only line print "NO". Otherwise, the first line should contain "YES". The next n lines should contain the pair of integers xi, yi (|xi|, |yi| ≤ 1018) — the coordinates of the point which corresponds to the i-th vertex of the tree. If there are several solutions, print any of them. Examples Input 7 1 2 1 3 2 4 2 5 3 6 3 7 Output YES 0 0 1 0 0 1 2 0 1 -1 -1 1 0 2 Input 6 1 2 2 3 2 4 2 5 2 6 Output NO Input 4 1 2 2 3 3 4 Output YES 3 3 4 3 5 3 6 3 Note In the first sample one of the possible positions of tree is: <image>
instruction
0
71,268
13
142,536
Tags: constructive algorithms, dfs and similar, graphs, greedy, trees Correct Solution: ``` def dfs(v, x, y, t, l, pr): ans[v] = x, y nx = [(l, 0), (0, -l), (-l, 0), (0, l)] if t == 0: p = 0, 1, 3 if t == 1: p = 0, 1, 2 if t == 2: p = 1, 2, 3 if t == 3: p = 0, 2, 3 listv = [u for u in g[v] if u != pr] g[v] = listv[:] for i in range(min(len(p), len(g[v]))): dx = nx[p[i]][0] dy = nx[p[i]][1] newx = x + dx newy = y + dy u = g[v][i] dfs(u, newx, newy, p[i], l // 4, v) read = lambda: map(int, input().split()) n = int(input()) g = [list() for i in range(n + 1)] for i in range(n - 1): u, v = read() g[u].append(v) g[v].append(u) def fail(): print('NO') exit() root = 1 for i in range(n + 1): if len(g[i]) > 4: fail() if len(g[i]) > len(g[root]): root = i ans = [0] * (n + 1) ans[root] = (0, 0) inf = 10 ** 18 l = inf // 4 nx = [(l, 0), (0, -l), (-l, 0), (0, l)] for i in range(len(g[root])): dx = nx[i][0] dy = nx[i][1] newx = 0 + dx newy = 0 + dy dfs(g[root][i], newx, newy, i, l // 4, root) print('YES') [print(*i) for i in ans[1:]] ```
output
1
71,268
13
142,537
Provide tags and a correct Python 3 solution for this coding contest problem. Dasha decided to have a rest after solving the problem. She had been ready to start her favourite activity — origami, but remembered the puzzle that she could not solve. <image> The tree is a non-oriented connected graph without cycles. In particular, there always are n - 1 edges in a tree with n vertices. The puzzle is to position the vertices at the points of the Cartesian plane with integral coordinates, so that the segments between the vertices connected by edges are parallel to the coordinate axes. Also, the intersection of segments is allowed only at their ends. Distinct vertices should be placed at different points. Help Dasha to find any suitable way to position the tree vertices on the plane. It is guaranteed that if it is possible to position the tree vertices on the plane without violating the condition which is given above, then you can do it by using points with integral coordinates which don't exceed 1018 in absolute value. Input The first line contains single integer n (1 ≤ n ≤ 30) — the number of vertices in the tree. Each of next n - 1 lines contains two integers ui, vi (1 ≤ ui, vi ≤ n) that mean that the i-th edge of the tree connects vertices ui and vi. It is guaranteed that the described graph is a tree. Output If the puzzle doesn't have a solution then in the only line print "NO". Otherwise, the first line should contain "YES". The next n lines should contain the pair of integers xi, yi (|xi|, |yi| ≤ 1018) — the coordinates of the point which corresponds to the i-th vertex of the tree. If there are several solutions, print any of them. Examples Input 7 1 2 1 3 2 4 2 5 3 6 3 7 Output YES 0 0 1 0 0 1 2 0 1 -1 -1 1 0 2 Input 6 1 2 2 3 2 4 2 5 2 6 Output NO Input 4 1 2 2 3 3 4 Output YES 3 3 4 3 5 3 6 3 Note In the first sample one of the possible positions of tree is: <image>
instruction
0
71,269
13
142,538
Tags: constructive algorithms, dfs and similar, graphs, greedy, trees Correct Solution: ``` n = int(input()) adj = [[] for _ in range(n)] for _ in range(n - 1): u, v = map(int, input().split()) adj[u - 1].append(v - 1) adj[v - 1].append(u - 1) from collections import deque def bfs(v): vis = [i == v for i in range(n)] paths = deque([[v]]) while paths: p = paths.popleft() for nv in adj[p[-1]]: if not vis[nv]: vis[nv] = True paths.append(p + [nv]) return p diameter = bfs(0) diameter = bfs(diameter[-1]) p = diameter[len(diameter) // 2] start = (0, 0) move = [(0, 1), (1, 0), (0, -1), (-1, 0)] gpt = lambda pt, i, dis : (pt[0] + move[i][0] * dis, pt[1] + move[i][1] * dis) vis = [False] * n dis = 2 ** (len(diameter) + 1) ans = [0] * n q = deque([(p, start, -1, dis)]) while q: p, start, dr, dis = q.popleft() vis[p] = True ans[p] = start if len(adj[p]) > 4: print("NO") exit() if dr == -1: drs = [i for i in range(4)] else: drs = [i for i in range(4) if gpt(move[i], dr, 1) != (0, 0)] for nv in adj[p]: if not vis[nv]: vis[nv], dr = True, drs.pop() npt = gpt(start, dr, dis) q.append((nv, npt, dr, dis // 2)) ans[nv] = npt print("YES") for pt in ans: print(*pt) ```
output
1
71,269
13
142,539
Provide tags and a correct Python 3 solution for this coding contest problem. Dasha decided to have a rest after solving the problem. She had been ready to start her favourite activity — origami, but remembered the puzzle that she could not solve. <image> The tree is a non-oriented connected graph without cycles. In particular, there always are n - 1 edges in a tree with n vertices. The puzzle is to position the vertices at the points of the Cartesian plane with integral coordinates, so that the segments between the vertices connected by edges are parallel to the coordinate axes. Also, the intersection of segments is allowed only at their ends. Distinct vertices should be placed at different points. Help Dasha to find any suitable way to position the tree vertices on the plane. It is guaranteed that if it is possible to position the tree vertices on the plane without violating the condition which is given above, then you can do it by using points with integral coordinates which don't exceed 1018 in absolute value. Input The first line contains single integer n (1 ≤ n ≤ 30) — the number of vertices in the tree. Each of next n - 1 lines contains two integers ui, vi (1 ≤ ui, vi ≤ n) that mean that the i-th edge of the tree connects vertices ui and vi. It is guaranteed that the described graph is a tree. Output If the puzzle doesn't have a solution then in the only line print "NO". Otherwise, the first line should contain "YES". The next n lines should contain the pair of integers xi, yi (|xi|, |yi| ≤ 1018) — the coordinates of the point which corresponds to the i-th vertex of the tree. If there are several solutions, print any of them. Examples Input 7 1 2 1 3 2 4 2 5 3 6 3 7 Output YES 0 0 1 0 0 1 2 0 1 -1 -1 1 0 2 Input 6 1 2 2 3 2 4 2 5 2 6 Output NO Input 4 1 2 2 3 3 4 Output YES 3 3 4 3 5 3 6 3 Note In the first sample one of the possible positions of tree is: <image>
instruction
0
71,270
13
142,540
Tags: constructive algorithms, dfs and similar, graphs, greedy, trees Correct Solution: ``` from collections import deque n = int(input()) dx = [-1, 0, 1, 0] dy = [0, -1, 0, 1] gr = [[] for i in range(n)] for i in range(n - 1): a, b = [int(i) for i in input().split()] a -= 1 b -= 1 gr[a].append(b) gr[b].append(a) for i in range(n): if len(gr[i]) > 4: print("NO") exit(0) print("YES") d = deque() d.append((0, 10 ** 18 // 2, 10 ** 18 // 2, -1, -1, 50)) ans = [0] * n while len(d) > 0: v = d[0][0] x = d[0][1] y = d[0][2] ans[v] = (d[0][1], d[0][2]) p = d[0][4] dr = d[0][3] pw = d[0][5] d.popleft() if p != -1: gr[v].pop(gr[v].index(p)) cur = 0 for i in range(4): if i == dr: continue if cur == len(gr[v]): break ngh = gr[v][cur] d.append((ngh, x + 2 ** pw * dx[i], y + 2 ** pw * dy[i], (i + 2) % 4, v, pw - 1)) cur += 1 for i in ans: print(*i) ```
output
1
71,270
13
142,541
Provide tags and a correct Python 3 solution for this coding contest problem. Dasha decided to have a rest after solving the problem. She had been ready to start her favourite activity — origami, but remembered the puzzle that she could not solve. <image> The tree is a non-oriented connected graph without cycles. In particular, there always are n - 1 edges in a tree with n vertices. The puzzle is to position the vertices at the points of the Cartesian plane with integral coordinates, so that the segments between the vertices connected by edges are parallel to the coordinate axes. Also, the intersection of segments is allowed only at their ends. Distinct vertices should be placed at different points. Help Dasha to find any suitable way to position the tree vertices on the plane. It is guaranteed that if it is possible to position the tree vertices on the plane without violating the condition which is given above, then you can do it by using points with integral coordinates which don't exceed 1018 in absolute value. Input The first line contains single integer n (1 ≤ n ≤ 30) — the number of vertices in the tree. Each of next n - 1 lines contains two integers ui, vi (1 ≤ ui, vi ≤ n) that mean that the i-th edge of the tree connects vertices ui and vi. It is guaranteed that the described graph is a tree. Output If the puzzle doesn't have a solution then in the only line print "NO". Otherwise, the first line should contain "YES". The next n lines should contain the pair of integers xi, yi (|xi|, |yi| ≤ 1018) — the coordinates of the point which corresponds to the i-th vertex of the tree. If there are several solutions, print any of them. Examples Input 7 1 2 1 3 2 4 2 5 3 6 3 7 Output YES 0 0 1 0 0 1 2 0 1 -1 -1 1 0 2 Input 6 1 2 2 3 2 4 2 5 2 6 Output NO Input 4 1 2 2 3 3 4 Output YES 3 3 4 3 5 3 6 3 Note In the first sample one of the possible positions of tree is: <image>
instruction
0
71,271
13
142,542
Tags: constructive algorithms, dfs and similar, graphs, greedy, trees Correct Solution: ``` def dfs(v, x, y, t, l, pr): ans[v] = x, y p = [(0, 1, 3), (0, 1, 2), (1, 2, 3), (0, 2, 3)][t] g[v] = [u for u in g[v] if u != pr] for i in range(min(len(p), len(g[v]))): newx = x + nx[p[i]][0] * l newy = y + nx[p[i]][1] * l dfs(g[v][i], newx, newy, p[i], l // 4, v) read = lambda: map(int, input().split()) n = int(input()) g = [list() for i in range(n + 1)] for i in range(n - 1): u, v = read() g[u].append(v) g[v].append(u) root = 1 for i in range(n + 1): if len(g[i]) > 4: print('NO') exit() ans = [0] * (n + 1) ans[root] = 0, 0 inf = 10 ** 18 l = inf // 4 nx = (1, 0), (0, -1), (-1, 0), (0, 1) for i in range(len(g[root])): dfs(g[root][i], nx[i][0] * l, nx[i][1] * l, i, l // 4, root) print('YES') [print(*i) for i in ans[1:]] ```
output
1
71,271
13
142,543
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Dasha decided to have a rest after solving the problem. She had been ready to start her favourite activity — origami, but remembered the puzzle that she could not solve. <image> The tree is a non-oriented connected graph without cycles. In particular, there always are n - 1 edges in a tree with n vertices. The puzzle is to position the vertices at the points of the Cartesian plane with integral coordinates, so that the segments between the vertices connected by edges are parallel to the coordinate axes. Also, the intersection of segments is allowed only at their ends. Distinct vertices should be placed at different points. Help Dasha to find any suitable way to position the tree vertices on the plane. It is guaranteed that if it is possible to position the tree vertices on the plane without violating the condition which is given above, then you can do it by using points with integral coordinates which don't exceed 1018 in absolute value. Input The first line contains single integer n (1 ≤ n ≤ 30) — the number of vertices in the tree. Each of next n - 1 lines contains two integers ui, vi (1 ≤ ui, vi ≤ n) that mean that the i-th edge of the tree connects vertices ui and vi. It is guaranteed that the described graph is a tree. Output If the puzzle doesn't have a solution then in the only line print "NO". Otherwise, the first line should contain "YES". The next n lines should contain the pair of integers xi, yi (|xi|, |yi| ≤ 1018) — the coordinates of the point which corresponds to the i-th vertex of the tree. If there are several solutions, print any of them. Examples Input 7 1 2 1 3 2 4 2 5 3 6 3 7 Output YES 0 0 1 0 0 1 2 0 1 -1 -1 1 0 2 Input 6 1 2 2 3 2 4 2 5 2 6 Output NO Input 4 1 2 2 3 3 4 Output YES 3 3 4 3 5 3 6 3 Note In the first sample one of the possible positions of tree is: <image> Submitted Solution: ``` #https://codeforces.com/problemset/problem/761/E def solve(): def push(u, v, g): if u not in g: g[u] = [] if v not in g: g[v] = [] g[u].append(v) g[v].append(u) n = int(input()) g = {} for _ in range(n-1): u, v = map(int, input().split()) push(u, v, g) for u in g: if len(g[u]) > 4: return 'NO', None d = {} build(1, 0, 0, 0, 31, -1, d, g) s = '' for u in range(1, n+1): x, y = d[u] s += str(x) + ' ' + str(y) s += '\n' return 'YES', s def cal_pos(dir_, cur_x, cur_y, cur_base): if dir_ == 0: return cur_x, cur_y + (1<<cur_base) elif dir_ == 1: return cur_x + (1<<cur_base), cur_y elif dir_ == 2: return cur_x, cur_y - (1<<cur_base) else: return cur_x - (1<<cur_base), cur_y def build(u, p, cur_x, cur_y, cur_base, pre_dir, d, g): d[u] = [cur_x, cur_y] type_ = [0,1,2,3] if pre_dir in type_: type_.remove(pre_dir) if u in g: for v in g[u]: if v != p: dir_ = type_.pop() next_x, next_y = cal_pos(dir_, cur_x, cur_y, cur_base) build(v, u, next_x, next_y, cur_base-1, (dir_ - 2)%4, d, g) ans ,s = solve() if ans == 'NO': print(ans) else: print(ans) print(s) ```
instruction
0
71,272
13
142,544
Yes
output
1
71,272
13
142,545
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Dasha decided to have a rest after solving the problem. She had been ready to start her favourite activity — origami, but remembered the puzzle that she could not solve. <image> The tree is a non-oriented connected graph without cycles. In particular, there always are n - 1 edges in a tree with n vertices. The puzzle is to position the vertices at the points of the Cartesian plane with integral coordinates, so that the segments between the vertices connected by edges are parallel to the coordinate axes. Also, the intersection of segments is allowed only at their ends. Distinct vertices should be placed at different points. Help Dasha to find any suitable way to position the tree vertices on the plane. It is guaranteed that if it is possible to position the tree vertices on the plane without violating the condition which is given above, then you can do it by using points with integral coordinates which don't exceed 1018 in absolute value. Input The first line contains single integer n (1 ≤ n ≤ 30) — the number of vertices in the tree. Each of next n - 1 lines contains two integers ui, vi (1 ≤ ui, vi ≤ n) that mean that the i-th edge of the tree connects vertices ui and vi. It is guaranteed that the described graph is a tree. Output If the puzzle doesn't have a solution then in the only line print "NO". Otherwise, the first line should contain "YES". The next n lines should contain the pair of integers xi, yi (|xi|, |yi| ≤ 1018) — the coordinates of the point which corresponds to the i-th vertex of the tree. If there are several solutions, print any of them. Examples Input 7 1 2 1 3 2 4 2 5 3 6 3 7 Output YES 0 0 1 0 0 1 2 0 1 -1 -1 1 0 2 Input 6 1 2 2 3 2 4 2 5 2 6 Output NO Input 4 1 2 2 3 3 4 Output YES 3 3 4 3 5 3 6 3 Note In the first sample one of the possible positions of tree is: <image> Submitted Solution: ``` def dfs(v, x, y, t, l, pr): ans[v] = x, y nx = [(-l, 0), (0, l), (l, 0), (0, -l)] if t == 0: p = 0, 1, 3 if t == 1: p = 0, 1, 2 if t == 2: p = 1, 2, 3 if t == 3: p = 0, 2, 3 listv = [u for u in g[v] if u != pr] g[v] = listv[:] for i in range(min(len(p), len(g[v]))): dx = nx[i][0] dy = nx[i][1] newx = x + dx newy = y + dy u = g[v][i] dfs(u, newx, newy, p[i], l // 4, v) read = lambda: map(int, input().split()) n = int(input()) g = [list() for i in range(n + 1)] for i in range(n - 1): u, v = read() g[u].append(v) g[v].append(u) def fail(): print('NO') exit() root = 1 for i in range(n + 1): if len(g[i]) > 4: fail() if len(g[i]) == 4: root = i ans = [0] * (n + 1) ans[root] = (0, 0) inf = 10 ** 18 l = inf // 4 nx = [(-l, 0), (0, l), (l, 0), (0, -l)] for i in range(len(g[root])): dx = nx[i][0] dy = nx[i][1] newx = 0 + dx newy = 0 + dy dfs(g[root][i], newx, newy, i, l // 4, root) print('YES') [print(*i) for i in ans[1:]] ```
instruction
0
71,273
13
142,546
No
output
1
71,273
13
142,547
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Dasha decided to have a rest after solving the problem. She had been ready to start her favourite activity — origami, but remembered the puzzle that she could not solve. <image> The tree is a non-oriented connected graph without cycles. In particular, there always are n - 1 edges in a tree with n vertices. The puzzle is to position the vertices at the points of the Cartesian plane with integral coordinates, so that the segments between the vertices connected by edges are parallel to the coordinate axes. Also, the intersection of segments is allowed only at their ends. Distinct vertices should be placed at different points. Help Dasha to find any suitable way to position the tree vertices on the plane. It is guaranteed that if it is possible to position the tree vertices on the plane without violating the condition which is given above, then you can do it by using points with integral coordinates which don't exceed 1018 in absolute value. Input The first line contains single integer n (1 ≤ n ≤ 30) — the number of vertices in the tree. Each of next n - 1 lines contains two integers ui, vi (1 ≤ ui, vi ≤ n) that mean that the i-th edge of the tree connects vertices ui and vi. It is guaranteed that the described graph is a tree. Output If the puzzle doesn't have a solution then in the only line print "NO". Otherwise, the first line should contain "YES". The next n lines should contain the pair of integers xi, yi (|xi|, |yi| ≤ 1018) — the coordinates of the point which corresponds to the i-th vertex of the tree. If there are several solutions, print any of them. Examples Input 7 1 2 1 3 2 4 2 5 3 6 3 7 Output YES 0 0 1 0 0 1 2 0 1 -1 -1 1 0 2 Input 6 1 2 2 3 2 4 2 5 2 6 Output NO Input 4 1 2 2 3 3 4 Output YES 3 3 4 3 5 3 6 3 Note In the first sample one of the possible positions of tree is: <image> Submitted Solution: ``` n = int(input()) p = [set() for i in range(n)] for j in range(n - 1): u, v = map(int, input().split()) p[u - 1].add(v - 1) p[v - 1].add(u - 1) s = [(0, 0)] * n t = [(0, 1 << 30, 7)] l = [1, 0, -1, 0, 1] while t: u, d, k = t.pop() x, y = s[u] i = 0 for v in p[u]: if i == k: i += 1 if i > 3: exit(print('NO')) p[v].remove(u) s[v] = (x + l[i] * d, y + l[i + 1] * d) t.append((v, d >> 1, 3 - i)) i += 1 print('YES') for q in s: print(*q) ```
instruction
0
71,274
13
142,548
No
output
1
71,274
13
142,549
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Dasha decided to have a rest after solving the problem. She had been ready to start her favourite activity — origami, but remembered the puzzle that she could not solve. <image> The tree is a non-oriented connected graph without cycles. In particular, there always are n - 1 edges in a tree with n vertices. The puzzle is to position the vertices at the points of the Cartesian plane with integral coordinates, so that the segments between the vertices connected by edges are parallel to the coordinate axes. Also, the intersection of segments is allowed only at their ends. Distinct vertices should be placed at different points. Help Dasha to find any suitable way to position the tree vertices on the plane. It is guaranteed that if it is possible to position the tree vertices on the plane without violating the condition which is given above, then you can do it by using points with integral coordinates which don't exceed 1018 in absolute value. Input The first line contains single integer n (1 ≤ n ≤ 30) — the number of vertices in the tree. Each of next n - 1 lines contains two integers ui, vi (1 ≤ ui, vi ≤ n) that mean that the i-th edge of the tree connects vertices ui and vi. It is guaranteed that the described graph is a tree. Output If the puzzle doesn't have a solution then in the only line print "NO". Otherwise, the first line should contain "YES". The next n lines should contain the pair of integers xi, yi (|xi|, |yi| ≤ 1018) — the coordinates of the point which corresponds to the i-th vertex of the tree. If there are several solutions, print any of them. Examples Input 7 1 2 1 3 2 4 2 5 3 6 3 7 Output YES 0 0 1 0 0 1 2 0 1 -1 -1 1 0 2 Input 6 1 2 2 3 2 4 2 5 2 6 Output NO Input 4 1 2 2 3 3 4 Output YES 3 3 4 3 5 3 6 3 Note In the first sample one of the possible positions of tree is: <image> Submitted Solution: ``` # ---------------------------iye ha aam zindegi--------------------------------------------- import math import random import heapq, bisect import sys from collections import deque, defaultdict from fractions import Fraction import sys #import threading from collections import defaultdict #threading.stack_size(10**8) mod = 10 ** 9 + 7 mod1 = 998244353 # ------------------------------warmup---------------------------- import os import sys from io import BytesIO, IOBase #sys.setrecursionlimit(300000) BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # -------------------game starts now----------------------------------------------------import math class TreeNode: def __init__(self, k, v): self.key = k self.value = v self.left = None self.right = None self.parent = None self.height = 1 self.num_left = 1 self.num_total = 1 class AvlTree: def __init__(self): self._tree = None def add(self, k, v): if not self._tree: self._tree = TreeNode(k, v) return node = self._add(k, v) if node: self._rebalance(node) def _add(self, k, v): node = self._tree while node: if k < node.key: if node.left: node = node.left else: node.left = TreeNode(k, v) node.left.parent = node return node.left elif node.key < k: if node.right: node = node.right else: node.right = TreeNode(k, v) node.right.parent = node return node.right else: node.value = v return @staticmethod def get_height(x): return x.height if x else 0 @staticmethod def get_num_total(x): return x.num_total if x else 0 def _rebalance(self, node): n = node while n: lh = self.get_height(n.left) rh = self.get_height(n.right) n.height = max(lh, rh) + 1 balance_factor = lh - rh n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right) n.num_left = 1 + self.get_num_total(n.left) if balance_factor > 1: if self.get_height(n.left.left) < self.get_height(n.left.right): self._rotate_left(n.left) self._rotate_right(n) elif balance_factor < -1: if self.get_height(n.right.right) < self.get_height(n.right.left): self._rotate_right(n.right) self._rotate_left(n) else: n = n.parent def _remove_one(self, node): """ Side effect!!! Changes node. Node should have exactly one child """ replacement = node.left or node.right if node.parent: if AvlTree._is_left(node): node.parent.left = replacement else: node.parent.right = replacement replacement.parent = node.parent node.parent = None else: self._tree = replacement replacement.parent = None node.left = None node.right = None node.parent = None self._rebalance(replacement) def _remove_leaf(self, node): if node.parent: if AvlTree._is_left(node): node.parent.left = None else: node.parent.right = None self._rebalance(node.parent) else: self._tree = None node.parent = None node.left = None node.right = None def remove(self, k): node = self._get_node(k) if not node: return if AvlTree._is_leaf(node): self._remove_leaf(node) return if node.left and node.right: nxt = AvlTree._get_next(node) node.key = nxt.key node.value = nxt.value if self._is_leaf(nxt): self._remove_leaf(nxt) else: self._remove_one(nxt) self._rebalance(node) else: self._remove_one(node) def get(self, k): node = self._get_node(k) return node.value if node else -1 def _get_node(self, k): if not self._tree: return None node = self._tree while node: if k < node.key: node = node.left elif node.key < k: node = node.right else: return node return None def get_at(self, pos): x = pos + 1 node = self._tree while node: if x < node.num_left: node = node.left elif node.num_left < x: x -= node.num_left node = node.right else: return (node.key, node.value) raise IndexError("Out of ranges") @staticmethod def _is_left(node): return node.parent.left and node.parent.left == node @staticmethod def _is_leaf(node): return node.left is None and node.right is None def _rotate_right(self, node): if not node.parent: self._tree = node.left node.left.parent = None elif AvlTree._is_left(node): node.parent.left = node.left node.left.parent = node.parent else: node.parent.right = node.left node.left.parent = node.parent bk = node.left.right node.left.right = node node.parent = node.left node.left = bk if bk: bk.parent = node node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1 node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right) node.num_left = 1 + self.get_num_total(node.left) def _rotate_left(self, node): if not node.parent: self._tree = node.right node.right.parent = None elif AvlTree._is_left(node): node.parent.left = node.right node.right.parent = node.parent else: node.parent.right = node.right node.right.parent = node.parent bk = node.right.left node.right.left = node node.parent = node.right node.right = bk if bk: bk.parent = node node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1 node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right) node.num_left = 1 + self.get_num_total(node.left) @staticmethod def _get_next(node): if not node.right: return node.parent n = node.right while n.left: n = n.left return n # -----------------------------------------------binary seacrh tree--------------------------------------- class SegmentTree1: def __init__(self, data, default=300006, func=lambda a, b: min(a , b)): """initialize the segment tree with data""" self._default = default self._func = func self._len = len(data) self._size = _size = 1 << (self._len - 1).bit_length() self.data = [default] * (2 * _size) self.data[_size:_size + self._len] = data for i in reversed(range(_size)): self.data[i] = func(self.data[i + i], self.data[i + i + 1]) def __delitem__(self, idx): self[idx] = self._default def __getitem__(self, idx): return self.data[idx + self._size] def __setitem__(self, idx, value): idx += self._size self.data[idx] = value idx >>= 1 while idx: self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) idx >>= 1 def __len__(self): return self._len def query(self, start, stop): if start == stop: return self.__getitem__(start) stop += 1 start += self._size stop += self._size res = self._default while start < stop: if start & 1: res = self._func(res, self.data[start]) start += 1 if stop & 1: stop -= 1 res = self._func(res, self.data[stop]) start >>= 1 stop >>= 1 return res def __repr__(self): return "SegmentTree({0})".format(self.data) # -------------------game starts now----------------------------------------------------import math class SegmentTree: def __init__(self, data, default=0, func=lambda a, b:a + b): """initialize the segment tree with data""" self._default = default self._func = func self._len = len(data) self._size = _size = 1 << (self._len - 1).bit_length() self.data = [default] * (2 * _size) self.data[_size:_size + self._len] = data for i in reversed(range(_size)): self.data[i] = func(self.data[i + i], self.data[i + i + 1]) def __delitem__(self, idx): self[idx] = self._default def __getitem__(self, idx): return self.data[idx + self._size] def __setitem__(self, idx, value): idx += self._size self.data[idx] = value idx >>= 1 while idx: self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) idx >>= 1 def __len__(self): return self._len def query(self, start, stop): if start == stop: return self.__getitem__(start) stop += 1 start += self._size stop += self._size res = self._default while start < stop: if start & 1: res = self._func(res, self.data[start]) start += 1 if stop & 1: stop -= 1 res = self._func(res, self.data[stop]) start >>= 1 stop >>= 1 return res def __repr__(self): return "SegmentTree({0})".format(self.data) # -------------------------------iye ha chutiya zindegi------------------------------------- class Factorial: def __init__(self, MOD): self.MOD = MOD self.factorials = [1, 1] self.invModulos = [0, 1] self.invFactorial_ = [1, 1] def calc(self, n): if n <= -1: print("Invalid argument to calculate n!") print("n must be non-negative value. But the argument was " + str(n)) exit() if n < len(self.factorials): return self.factorials[n] nextArr = [0] * (n + 1 - len(self.factorials)) initialI = len(self.factorials) prev = self.factorials[-1] m = self.MOD for i in range(initialI, n + 1): prev = nextArr[i - initialI] = prev * i % m self.factorials += nextArr return self.factorials[n] def inv(self, n): if n <= -1: print("Invalid argument to calculate n^(-1)") print("n must be non-negative value. But the argument was " + str(n)) exit() p = self.MOD pi = n % p if pi < len(self.invModulos): return self.invModulos[pi] nextArr = [0] * (n + 1 - len(self.invModulos)) initialI = len(self.invModulos) for i in range(initialI, min(p, n + 1)): next = -self.invModulos[p % i] * (p // i) % p self.invModulos.append(next) return self.invModulos[pi] def invFactorial(self, n): if n <= -1: print("Invalid argument to calculate (n^(-1))!") print("n must be non-negative value. But the argument was " + str(n)) exit() if n < len(self.invFactorial_): return self.invFactorial_[n] self.inv(n) # To make sure already calculated n^-1 nextArr = [0] * (n + 1 - len(self.invFactorial_)) initialI = len(self.invFactorial_) prev = self.invFactorial_[-1] p = self.MOD for i in range(initialI, n + 1): prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p self.invFactorial_ += nextArr return self.invFactorial_[n] class Combination: def __init__(self, MOD): self.MOD = MOD self.factorial = Factorial(MOD) def ncr(self, n, k): if k < 0 or n < k: return 0 k = min(k, n - k) f = self.factorial return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD # --------------------------------------iye ha combinations ka zindegi--------------------------------- def powm(a, n, m): if a == 1 or n == 0: return 1 if n % 2 == 0: s = powm(a, n // 2, m) return s * s % m else: return a * powm(a, n - 1, m) % m # --------------------------------------iye ha power ka zindegi--------------------------------- def sort_list(list1, list2): zipped_pairs = zip(list2, list1) z = [x for _, x in sorted(zipped_pairs)] return z # --------------------------------------------------product---------------------------------------- def product(l): por = 1 for i in range(len(l)): por *= l[i] return por # --------------------------------------------------binary---------------------------------------- def binarySearchCount(arr, n, key): left = 0 right = n - 1 count = 0 while (left <= right): mid = int((right + left) / 2) # Check if middle element is # less than or equal to key if (arr[mid] <key): count = mid + 1 left = mid + 1 # If key is smaller, ignore right half else: right = mid - 1 return count # --------------------------------------------------binary---------------------------------------- def countdig(n): c = 0 while (n > 0): n //= 10 c += 1 return c def binary(x, length): y = bin(x)[2:] return y if len(y) >= length else "0" * (length - len(y)) + y def countGreater(arr, n, k): l = 0 r = n - 1 # Stores the index of the left most element # from the array which is greater than k leftGreater = n # Finds number of elements greater than k while (l <= r): m = int(l + (r - l) / 2) if (arr[m] >= k): leftGreater = m r = m - 1 # If mid element is less than # or equal to k update l else: l = m + 1 # Return the count of elements # greater than k return (n - leftGreater) # --------------------------------------------------binary------------------------------------ class TrieNode: def __init__(self): self.children = [None] * 26 self.isEndOfWord = False class Trie: def __init__(self): self.root = self.getNode() def getNode(self): return TrieNode() def _charToIndex(self, ch): return ord(ch) - ord('a') def insert(self, key): pCrawl = self.root length = len(key) for level in range(length): index = self._charToIndex(key[level]) if not pCrawl.children[index]: pCrawl.children[index] = self.getNode() pCrawl = pCrawl.children[index] pCrawl.isEndOfWord = True def search(self, key): pCrawl = self.root length = len(key) for level in range(length): index = self._charToIndex(key[level]) if not pCrawl.children[index]: return False pCrawl = pCrawl.children[index] return pCrawl != None and pCrawl.isEndOfWord #-----------------------------------------trie--------------------------------- class Node: def __init__(self, data): self.data = data self.height=0 self.left = None # left node for 0 self.right = None # right node for 1 class BinaryTrie: def __init__(self): self.root = Node(0) def insert(self, pre_xor): self.temp = self.root for i in range(31, -1, -1): val = pre_xor & (1 << i) if val==0: if not self.temp.right: self.temp.right = Node(0) self.temp = self.temp.right elif val>=1: if not self.temp.left: self.temp.left = Node(0) self.temp = self.temp.left def do(self,temp): if not temp: return 0 ter=temp temp.height=self.do(ter.left)+self.do(ter.right) if temp.height==0: temp.height+=1 return temp.height def query(self, xor): self.temp = self.root cur=0 i=31 while(i>-1): val = xor & (1 << i) if not self.temp: return cur if val>=1: self.opp = self.temp.right if self.temp.left: self.temp = self.temp.left else: return cur else: self.opp=self.temp.left if self.temp.right: self.temp = self.temp.right else: return cur if self.temp.height==pow(2,i): cur+=1<<(i) self.temp=self.opp i-=1 return cur #-------------------------bin trie------------------------------------------- n=int(input()) ans=[(0,0) for i in range(n)] done=set() def dfs(v,a,b,d,p): ans[v]=(a,b) t=0 w=[(1,0),(0,1),(-1,0),(0,-1)] for i in graph[v]: if i==p: continue dfs(i,a+d*w[t][0],b+d*w[t][1],d//2,v) t+=1 graph=defaultdict(list) d=defaultdict(int) for i in range(n-1): x,y=map(int,input().split()) d[x-1]+=1 d[y-1]+=1 graph[x-1].append(y-1) graph[y-1].append(x-1) if max(d.values())>4: print("NO") else: dfs(0,0,0,2**58,-1) print("YES") for i in range(n): print(*ans[i]) ```
instruction
0
71,275
13
142,550
No
output
1
71,275
13
142,551
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Dasha decided to have a rest after solving the problem. She had been ready to start her favourite activity — origami, but remembered the puzzle that she could not solve. <image> The tree is a non-oriented connected graph without cycles. In particular, there always are n - 1 edges in a tree with n vertices. The puzzle is to position the vertices at the points of the Cartesian plane with integral coordinates, so that the segments between the vertices connected by edges are parallel to the coordinate axes. Also, the intersection of segments is allowed only at their ends. Distinct vertices should be placed at different points. Help Dasha to find any suitable way to position the tree vertices on the plane. It is guaranteed that if it is possible to position the tree vertices on the plane without violating the condition which is given above, then you can do it by using points with integral coordinates which don't exceed 1018 in absolute value. Input The first line contains single integer n (1 ≤ n ≤ 30) — the number of vertices in the tree. Each of next n - 1 lines contains two integers ui, vi (1 ≤ ui, vi ≤ n) that mean that the i-th edge of the tree connects vertices ui and vi. It is guaranteed that the described graph is a tree. Output If the puzzle doesn't have a solution then in the only line print "NO". Otherwise, the first line should contain "YES". The next n lines should contain the pair of integers xi, yi (|xi|, |yi| ≤ 1018) — the coordinates of the point which corresponds to the i-th vertex of the tree. If there are several solutions, print any of them. Examples Input 7 1 2 1 3 2 4 2 5 3 6 3 7 Output YES 0 0 1 0 0 1 2 0 1 -1 -1 1 0 2 Input 6 1 2 2 3 2 4 2 5 2 6 Output NO Input 4 1 2 2 3 3 4 Output YES 3 3 4 3 5 3 6 3 Note In the first sample one of the possible positions of tree is: <image> Submitted Solution: ``` def dfs(v, x, y, t, l, pr): ans[v] = x, y nx = [(-l, 0), (0, l), (l, 0), (0, -l)] if t == 0: p = 0, 1, 3 if t == 1: p = 0, 1, 2 if t == 2: p = 1, 2, 3 if t == 3: p = 0, 2, 3 listv = [u for u in g[v] if u != pr] g[v] = listv[:] for i in range(min(len(p), len(g[v]))): dx = nx[i][0] dy = nx[i][1] newx = x + dx newy = y + dy u = g[v][i] dfs(u, newx, newy, p[i], l // 3 - 10, v) read = lambda: map(int, input().split()) n = int(input()) g = [list() for i in range(n + 1)] for i in range(n - 1): u, v = read() g[u].append(v) g[v].append(u) def fail(): print('NO') exit() root = 1 for i in range(n + 1): if len(g[i]) > 4: fail() if len(g[i]) == 4: root = i ans = [0] * (n + 1) ans[root] = (0, 0) inf = 10 ** 18 l = inf // 3 - 10 nx = [(-l, 0), (0, l), (l, 0), (0, -l)] for i in range(len(g[root])): dx = nx[i][0] dy = nx[i][1] newx = 0 + dx newy = 0 + dy dfs(g[root][i], newx, newy, i, l // 3 - 10, root) print('YES') [print(*i) for i in ans[1:]] ```
instruction
0
71,276
13
142,552
No
output
1
71,276
13
142,553
Provide a correct Python 3 solution for this coding contest problem. Coloring of the vertices of a tree G is called a good coloring when, for every pair of two vertices u and v painted in the same color, picking u as the root and picking v as the root would result in isomorphic rooted trees. Also, the colorfulness of G is defined as the minimum possible number of different colors used in a good coloring of G. You are given a tree with N vertices. The vertices are numbered 1 through N, and the i-th edge connects Vertex a_i and Vertex b_i. We will construct a new tree T by repeating the following operation on this tree some number of times: * Add a new vertex to the tree by connecting it to one of the vertices in the current tree with an edge. Find the minimum possible colorfulness of T. Additionally, print the minimum number of leaves (vertices with degree 1) in a tree T that achieves the minimum colorfulness. Constraints * 2 \leq N \leq 100 * 1 \leq a_i,b_i \leq N(1\leq i\leq N-1) * The given graph is a tree. Input Input is given from Standard Input in the following format: N a_1 b_1 : a_{N-1} b_{N-1} Output Print two integers with a space in between. First, print the minimum possible colorfulness of a tree T that can be constructed. Second, print the minimum number of leaves in a tree that achieves it. It can be shown that, under the constraints of this problem, the values that should be printed fit into 64-bit signed integers. Examples Input 5 1 2 2 3 3 4 3 5 Output 2 4 Input 8 1 2 2 3 4 3 5 4 6 7 6 8 3 6 Output 3 4 Input 10 1 2 2 3 3 4 4 5 5 6 6 7 3 8 5 9 3 10 Output 4 6 Input 13 5 6 6 4 2 8 4 7 8 9 3 2 10 4 11 10 2 4 13 10 1 8 12 1 Output 4 12
instruction
0
71,455
13
142,910
"Correct Solution: ``` #!usr/bin/env python3 from collections import defaultdict,deque from heapq import heappush, heappop import sys import math import bisect import random def LI(): return [int(x) for x in sys.stdin.readline().split()] def I(): return int(sys.stdin.readline()) def LS():return [list(x) for x in sys.stdin.readline().split()] def S(): res = list(sys.stdin.readline()) if res[-1] == "\n": return res[:-1] return res def IR(n): return [I() for i in range(n)] def LIR(n): return [LI() for i in range(n)] def SR(n): return [S() for i in range(n)] def LSR(n): return [LS() for i in range(n)] sys.setrecursionlimit(1000000) mod = 1000000007 def solve(): n = I() v = [[] for i in range(n)] d = [[float("inf")]*n for i in range(n)] f = [-1]*n for i in range(n): d[i][i] = 0 for i in range(n-1): a,b = LI() a -= 1 b -= 1 d[a][b] = 1 d[b][a] = 1 f[a] += 1 f[b] += 1 v[a].append(b) v[b].append(a) for k in range(n): for i in range(n): for j in range(n): nd = d[i][k]+d[k][j] if nd < d[i][j]: d[i][j] = nd for i in range(n): f[i] = max(f[i],1) x = 0 for i in range(n): if d[0][x] < d[0][i]: x = i y = 0 for i in range(n): if d[x][y] < d[x][i]: y = i k = (d[x][y]>>1)+1 ans = float("inf") for s in range(n): if max(d[s]) < k: m = [0]*k m[0] = f[s]+1 for i in range(n): fi = f[i] di = d[s][i] if m[di] < fi: m[di] = fi na = 1 for i in m: na *= i if na < ans: ans = na for t in v[s]: nd = [min(d[s][i],d[t][i]) for i in range(n)] if max(nd) < k: m = [0]*k m[0] = max(nd[s],nd[t])+1 for i in range(n): fi = f[i] di = nd[i] if m[di] < fi: m[di] = fi na = 2 for i in m: na *= i if na < ans: ans = na print(k,ans) return #Solve if __name__ == "__main__": solve() ```
output
1
71,455
13
142,911
Provide a correct Python 3 solution for this coding contest problem. Coloring of the vertices of a tree G is called a good coloring when, for every pair of two vertices u and v painted in the same color, picking u as the root and picking v as the root would result in isomorphic rooted trees. Also, the colorfulness of G is defined as the minimum possible number of different colors used in a good coloring of G. You are given a tree with N vertices. The vertices are numbered 1 through N, and the i-th edge connects Vertex a_i and Vertex b_i. We will construct a new tree T by repeating the following operation on this tree some number of times: * Add a new vertex to the tree by connecting it to one of the vertices in the current tree with an edge. Find the minimum possible colorfulness of T. Additionally, print the minimum number of leaves (vertices with degree 1) in a tree T that achieves the minimum colorfulness. Constraints * 2 \leq N \leq 100 * 1 \leq a_i,b_i \leq N(1\leq i\leq N-1) * The given graph is a tree. Input Input is given from Standard Input in the following format: N a_1 b_1 : a_{N-1} b_{N-1} Output Print two integers with a space in between. First, print the minimum possible colorfulness of a tree T that can be constructed. Second, print the minimum number of leaves in a tree that achieves it. It can be shown that, under the constraints of this problem, the values that should be printed fit into 64-bit signed integers. Examples Input 5 1 2 2 3 3 4 3 5 Output 2 4 Input 8 1 2 2 3 4 3 5 4 6 7 6 8 3 6 Output 3 4 Input 10 1 2 2 3 3 4 4 5 5 6 6 7 3 8 5 9 3 10 Output 4 6 Input 13 5 6 6 4 2 8 4 7 8 9 3 2 10 4 11 10 2 4 13 10 1 8 12 1 Output 4 12
instruction
0
71,456
13
142,912
"Correct Solution: ``` n = int(input()) ab = [list(map(int,input().split())) for i in range(n-1)] graph = [[] for i in range(n+1)] for a,b in ab: graph[a].append(b) graph[b].append(a) ansls = [] for i in range(1,n+1): root = i stack = [i] dist = [-1 for i in range(n+1)] dist[root] = 0 while stack: x = stack.pop() for y in graph[x]: if dist[y] == -1: dist[y] = dist[x]+1 stack.append(y) mxd = max(dist) dls = [1 for i in range(mxd+1)] dls[0] = len(graph[root]) ans1 = mxd+1 ans2 = 1 for j in range(1,n+1): d = dist[j] dls[d] = max(dls[d],len(graph[j])-1) for x in dls: ans2 *= x ansls.append((ans1,ans2)) for i in range(n-1): r1,r2 = ab[i] stack = [r1,r2] dist = [-1 for i in range(n+1)] dist[r1] = 0 dist[r2] = 0 while stack: x = stack.pop() for y in graph[x]: if dist[y] == -1: dist[y] = dist[x]+1 stack.append(y) mxd = max(dist) dls = [1 for i in range(mxd+1)] ans1 = mxd+1 ans2 = 2 for j in range(1,n+1): d = dist[j] dls[d] = max(dls[d],len(graph[j])-1) for x in dls: ans2 *= x ansls.append((ans1,ans2)) ansls.sort() print(*ansls[0]) ```
output
1
71,456
13
142,913
Provide a correct Python 3 solution for this coding contest problem. Coloring of the vertices of a tree G is called a good coloring when, for every pair of two vertices u and v painted in the same color, picking u as the root and picking v as the root would result in isomorphic rooted trees. Also, the colorfulness of G is defined as the minimum possible number of different colors used in a good coloring of G. You are given a tree with N vertices. The vertices are numbered 1 through N, and the i-th edge connects Vertex a_i and Vertex b_i. We will construct a new tree T by repeating the following operation on this tree some number of times: * Add a new vertex to the tree by connecting it to one of the vertices in the current tree with an edge. Find the minimum possible colorfulness of T. Additionally, print the minimum number of leaves (vertices with degree 1) in a tree T that achieves the minimum colorfulness. Constraints * 2 \leq N \leq 100 * 1 \leq a_i,b_i \leq N(1\leq i\leq N-1) * The given graph is a tree. Input Input is given from Standard Input in the following format: N a_1 b_1 : a_{N-1} b_{N-1} Output Print two integers with a space in between. First, print the minimum possible colorfulness of a tree T that can be constructed. Second, print the minimum number of leaves in a tree that achieves it. It can be shown that, under the constraints of this problem, the values that should be printed fit into 64-bit signed integers. Examples Input 5 1 2 2 3 3 4 3 5 Output 2 4 Input 8 1 2 2 3 4 3 5 4 6 7 6 8 3 6 Output 3 4 Input 10 1 2 2 3 3 4 4 5 5 6 6 7 3 8 5 9 3 10 Output 4 6 Input 13 5 6 6 4 2 8 4 7 8 9 3 2 10 4 11 10 2 4 13 10 1 8 12 1 Output 4 12
instruction
0
71,457
13
142,914
"Correct Solution: ``` import sys input = sys.stdin.readline sys.setrecursionlimit(pow(10, 6)) from collections import deque edges = [] def solve(u, v=-1): global edges que = deque([u]) if v != -1: que.append(v) used = set([u, v]) D = {u: 0, v: 0} E = {} if v != -1: E[0] = max(len(edges[v]), len(edges[u])) - 1 else: E[0] = len(edges[u]) x = v while que: v = que.popleft() d = D[v] for w in edges[v]: if w in used: continue D[w] = d + 1 que.append(w) used.add(w) E[d+1] = max(E.get(d+1, 0), len(edges[w])-1) res = 2 if x != -1 else 1 for v in E.values(): if v: res *= v return res def main(): global edges n = int(input()) edges = [[] for _ in range(n)] for _ in range(n-1): a, b = map(int, input().split()) edges[a-1].append(b-1) edges[b-1].append(a-1) # calc diameter que = deque([0]) dist = {0: 0} prev = {0: 0} while que: u = que.popleft() d = dist[u] for w in edges[u]: if w in dist: continue dist[w] = d + 1 prev[w] = u que.append(w) w = u # 最遠点 que = deque([w]) dist = {w: 0} prev = {w: -1} while que: u = que.popleft() d = dist[u] for w in edges[u]: if w in dist: continue dist[w] = d + 1 prev[w] = u que.append(w) w = u D = [] while w != -1: D.append(w) w = prev[w] L = len(D) # 直径 col = (L + 1) // 2 if L % 2 == 1: ans = 10**18 v = D[L//2] # 中心 for w in edges[v]: # 中心から繋がってる部分について ans = min(ans, solve(v, w)) ans = min(ans, solve(v)) else: # 直径が偶数の時は中心が2個 v = D[L//2-1] w = D[L//2] ans = solve(v, w) print(col, ans) if __name__ == '__main__': main() ```
output
1
71,457
13
142,915
Provide a correct Python 3 solution for this coding contest problem. Coloring of the vertices of a tree G is called a good coloring when, for every pair of two vertices u and v painted in the same color, picking u as the root and picking v as the root would result in isomorphic rooted trees. Also, the colorfulness of G is defined as the minimum possible number of different colors used in a good coloring of G. You are given a tree with N vertices. The vertices are numbered 1 through N, and the i-th edge connects Vertex a_i and Vertex b_i. We will construct a new tree T by repeating the following operation on this tree some number of times: * Add a new vertex to the tree by connecting it to one of the vertices in the current tree with an edge. Find the minimum possible colorfulness of T. Additionally, print the minimum number of leaves (vertices with degree 1) in a tree T that achieves the minimum colorfulness. Constraints * 2 \leq N \leq 100 * 1 \leq a_i,b_i \leq N(1\leq i\leq N-1) * The given graph is a tree. Input Input is given from Standard Input in the following format: N a_1 b_1 : a_{N-1} b_{N-1} Output Print two integers with a space in between. First, print the minimum possible colorfulness of a tree T that can be constructed. Second, print the minimum number of leaves in a tree that achieves it. It can be shown that, under the constraints of this problem, the values that should be printed fit into 64-bit signed integers. Examples Input 5 1 2 2 3 3 4 3 5 Output 2 4 Input 8 1 2 2 3 4 3 5 4 6 7 6 8 3 6 Output 3 4 Input 10 1 2 2 3 3 4 4 5 5 6 6 7 3 8 5 9 3 10 Output 4 6 Input 13 5 6 6 4 2 8 4 7 8 9 3 2 10 4 11 10 2 4 13 10 1 8 12 1 Output 4 12
instruction
0
71,458
13
142,916
"Correct Solution: ``` from collections import deque N = int(input()) ab = [] dic = {} for i in range(N-1): a,b = map(int,input().split()) a -= 1 b -= 1 ab.append([a,b]) if a not in dic: dic[a] = [] if b not in dic: dic[b] = [] dic[a].append(b) dic[b].append(a) ans = float("inf") ansleef = float("inf") for r in range(N): leef = [0] * N q = deque([r]) dep = [float("inf")] * N dep[r] = 0 maxdep = 0 while len(q) > 0: now = q.popleft() nchild = 0 for i in dic[now]: if dep[i] > dep[now] + 1: nchild += 1 dep[i] = dep[now] + 1 maxdep = max(maxdep,dep[i]) q.append(i) leef[dep[now]] = max(leef[dep[now]],nchild) if ans > maxdep: ans = maxdep nl = 1 for i in range(maxdep): nl *= leef[i] ansleef = nl if ans == maxdep: ans = maxdep nl = 1 for i in range(maxdep): nl *= leef[i] ansleef = min(ansleef,nl) #print (ans + 1,ansleef) for r in range(N-1): leef = [0] * N pa = ab[r][0] pb = ab[r][1] q = deque([pa,pb]) dep = [float("inf")] * N dep[pa] = 0 dep[pb] = 0 maxdep = 0 while len(q) > 0: now = q.popleft() nchild = 0 for i in dic[now]: if dep[i] > dep[now] + 1: nchild += 1 dep[i] = dep[now] + 1 maxdep = max(maxdep,dep[i]) q.append(i) leef[dep[now]] = max(leef[dep[now]],nchild) if ans > maxdep: ans = maxdep nl = 2 for i in range(maxdep): nl *= leef[i] ansleef = nl if ans == maxdep: ans = maxdep nl = 2 for i in range(maxdep): nl *= leef[i] ansleef = min(ansleef,nl) print (ans + 1,ansleef) ```
output
1
71,458
13
142,917
Provide a correct Python 3 solution for this coding contest problem. Coloring of the vertices of a tree G is called a good coloring when, for every pair of two vertices u and v painted in the same color, picking u as the root and picking v as the root would result in isomorphic rooted trees. Also, the colorfulness of G is defined as the minimum possible number of different colors used in a good coloring of G. You are given a tree with N vertices. The vertices are numbered 1 through N, and the i-th edge connects Vertex a_i and Vertex b_i. We will construct a new tree T by repeating the following operation on this tree some number of times: * Add a new vertex to the tree by connecting it to one of the vertices in the current tree with an edge. Find the minimum possible colorfulness of T. Additionally, print the minimum number of leaves (vertices with degree 1) in a tree T that achieves the minimum colorfulness. Constraints * 2 \leq N \leq 100 * 1 \leq a_i,b_i \leq N(1\leq i\leq N-1) * The given graph is a tree. Input Input is given from Standard Input in the following format: N a_1 b_1 : a_{N-1} b_{N-1} Output Print two integers with a space in between. First, print the minimum possible colorfulness of a tree T that can be constructed. Second, print the minimum number of leaves in a tree that achieves it. It can be shown that, under the constraints of this problem, the values that should be printed fit into 64-bit signed integers. Examples Input 5 1 2 2 3 3 4 3 5 Output 2 4 Input 8 1 2 2 3 4 3 5 4 6 7 6 8 3 6 Output 3 4 Input 10 1 2 2 3 3 4 4 5 5 6 6 7 3 8 5 9 3 10 Output 4 6 Input 13 5 6 6 4 2 8 4 7 8 9 3 2 10 4 11 10 2 4 13 10 1 8 12 1 Output 4 12
instruction
0
71,459
13
142,918
"Correct Solution: ``` import sys read = sys.stdin.buffer.read readline = sys.stdin.buffer.readline readlines = sys.stdin.buffer.readlines sys.setrecursionlimit(10 ** 7) """ ・中心が同型不変であることを利用して考える。 ・カラフル度はだいたい直径の半分。 ・中心が頂点になる場合は、中心を隣接する辺に持ってこれる。Nが小さいので全部計算してもよい ・そもそもすべての辺、頂点に対して、そこを中心とする場合の(色数、葉数)を計算してもよい """ N,*AB = map(int,read().split()) AB = tuple(zip(*[iter(AB)]*2)) AB graph = [[] for _ in range(N+1)] for a,b in AB: graph[a].append(b) graph[b].append(a) deg = [len(x) for x in graph] graph,deg def F(centroids): """ ・中心とする1点または2点を与える ・できる木の(深さ,葉の数)を返す """ Ncent = len(centroids) depth = [None] * (N+1) q = centroids for x in q: depth[x] = 0 while q: x = q.pop() for y in graph[x]: if depth[y] is None: depth[y] = depth[x] + 1 q.append(y) D = max(depth[1:]) sep = [1] * (D+1) for x in range(1,N+1): d = depth[x] n = deg[x] - 1 sep[d] = max(sep[d],n) if Ncent == 1: sep[0] += 1 x = 1 for s in sep[:D]: x *= s if Ncent == 2: x *= 2 return D+1,x arr = [F([v]) for v in range(1,N+1)] + [F([a,b]) for a,b in AB] arr.sort() answer = arr[0] print(*answer) ```
output
1
71,459
13
142,919
Provide a correct Python 3 solution for this coding contest problem. Coloring of the vertices of a tree G is called a good coloring when, for every pair of two vertices u and v painted in the same color, picking u as the root and picking v as the root would result in isomorphic rooted trees. Also, the colorfulness of G is defined as the minimum possible number of different colors used in a good coloring of G. You are given a tree with N vertices. The vertices are numbered 1 through N, and the i-th edge connects Vertex a_i and Vertex b_i. We will construct a new tree T by repeating the following operation on this tree some number of times: * Add a new vertex to the tree by connecting it to one of the vertices in the current tree with an edge. Find the minimum possible colorfulness of T. Additionally, print the minimum number of leaves (vertices with degree 1) in a tree T that achieves the minimum colorfulness. Constraints * 2 \leq N \leq 100 * 1 \leq a_i,b_i \leq N(1\leq i\leq N-1) * The given graph is a tree. Input Input is given from Standard Input in the following format: N a_1 b_1 : a_{N-1} b_{N-1} Output Print two integers with a space in between. First, print the minimum possible colorfulness of a tree T that can be constructed. Second, print the minimum number of leaves in a tree that achieves it. It can be shown that, under the constraints of this problem, the values that should be printed fit into 64-bit signed integers. Examples Input 5 1 2 2 3 3 4 3 5 Output 2 4 Input 8 1 2 2 3 4 3 5 4 6 7 6 8 3 6 Output 3 4 Input 10 1 2 2 3 3 4 4 5 5 6 6 7 3 8 5 9 3 10 Output 4 6 Input 13 5 6 6 4 2 8 4 7 8 9 3 2 10 4 11 10 2 4 13 10 1 8 12 1 Output 4 12
instruction
0
71,460
13
142,920
"Correct Solution: ``` import sys N=int(input()) edge=[[] for i in range(N)] for i in range(N-1): a,b=map(int,input().split()) edge[a-1].append(b-1) edge[b-1].append(a-1) ans=(10**15,10**15) root=-1 depth=[0]*N Mdata=[0]*100 def dfs(v,pv): for nv in edge[v]: if nv!=pv: depth[nv]=depth[v]+1 Mdata[depth[nv]]=max(Mdata[depth[nv]],len(edge[nv])-1) dfs(nv,v) for i in range(N): depth=[0]*N Mdata=[0]*100 Mdata[0]=len(edge[i]) dfs(i,-1) tempc=max(depth)+1 res=1 for j in range(N): if Mdata[j]!=0: res*=Mdata[j] else: break ans=min(ans,(tempc,res)) #print(ans) for i in range(N): for j in edge[i]: depth=[0]*N Mdata=[0]*100 depth[i]=1 depth[j]=1 Mdata[1]=max(len(edge[i]),len(edge[j]))-1 Mdata[0]=2 dfs(i,j) dfs(j,i) tempc=max(depth) res=1 for k in range(N): if Mdata[k]!=0: res*=Mdata[k] else: break ans=min(ans,(tempc,res)) print(*ans) ```
output
1
71,460
13
142,921
Provide a correct Python 3 solution for this coding contest problem. Coloring of the vertices of a tree G is called a good coloring when, for every pair of two vertices u and v painted in the same color, picking u as the root and picking v as the root would result in isomorphic rooted trees. Also, the colorfulness of G is defined as the minimum possible number of different colors used in a good coloring of G. You are given a tree with N vertices. The vertices are numbered 1 through N, and the i-th edge connects Vertex a_i and Vertex b_i. We will construct a new tree T by repeating the following operation on this tree some number of times: * Add a new vertex to the tree by connecting it to one of the vertices in the current tree with an edge. Find the minimum possible colorfulness of T. Additionally, print the minimum number of leaves (vertices with degree 1) in a tree T that achieves the minimum colorfulness. Constraints * 2 \leq N \leq 100 * 1 \leq a_i,b_i \leq N(1\leq i\leq N-1) * The given graph is a tree. Input Input is given from Standard Input in the following format: N a_1 b_1 : a_{N-1} b_{N-1} Output Print two integers with a space in between. First, print the minimum possible colorfulness of a tree T that can be constructed. Second, print the minimum number of leaves in a tree that achieves it. It can be shown that, under the constraints of this problem, the values that should be printed fit into 64-bit signed integers. Examples Input 5 1 2 2 3 3 4 3 5 Output 2 4 Input 8 1 2 2 3 4 3 5 4 6 7 6 8 3 6 Output 3 4 Input 10 1 2 2 3 3 4 4 5 5 6 6 7 3 8 5 9 3 10 Output 4 6 Input 13 5 6 6 4 2 8 4 7 8 9 3 2 10 4 11 10 2 4 13 10 1 8 12 1 Output 4 12
instruction
0
71,461
13
142,922
"Correct Solution: ``` import sys input = sys.stdin.readline N=int(input()) E=[tuple(map(int,input().split())) for i in range(N-1)] ELIST=[[] for i in range(N+1)] EDEG=[0]*(N+1) for x,y in E: ELIST[x].append(y) ELIST[y].append(x) EDEG[x]+=1 EDEG[y]+=1 from collections import deque Q=deque() Q.append(1) H=[-1]*(N+1) H[1]=0 while Q: x=Q.pop() for to in ELIST[x]: if H[to]==-1: H[to]=H[x]+1 Q.append(to) MAXH=max(H) Q=deque() xi=H.index(MAXH) Q.append(xi) H=[-1]*(N+1) H[xi]=0 while Q: x=Q.pop() for to in ELIST[x]: if H[to]==-1: H[to]=H[x]+1 Q.append(to) MAXH=max(H) Q=deque() xi=H.index(MAXH) Q.append(xi) H2=[-1]*(N+1) H2[xi]=0 while Q: x=Q.pop() for to in ELIST[x]: if H2[to]==-1: H2[to]=H2[x]+1 Q.append(to) ANS1=(max(H)+2)//2 print(ANS1) #print(H) #print(H2) if MAXH%2==1: Q=deque() USE=[0]*(N+1) for i in range(N+1): if (H[i]==MAXH//2 and H2[i]==MAXH//2+1) or (H[i]==MAXH//2+1 and H2[i]==MAXH//2): Q.append(i) USE[i]=1 ANS2=1 #print(Q) while Q: NQ=deque() score=1 while Q: x=Q.pop() USE[x]=1 score=max(score,len(ELIST[x])-1) for to in ELIST[x]: if USE[to]==1: continue NQ.append(to) ANS2*=score Q=NQ print(ANS2*2) else: Q=deque() for i in range(N+1): if H[i]==MAXH//2 and H2[i]==MAXH//2: Q.append(i) MID=i ANS2=len(ELIST[MID]) USE=[0]*(N+1) #print(Q) while Q: NQ=deque() score=1 while Q: x=Q.pop() USE[x]=1 if x!=MID: score=max(score,len(ELIST[x])-1) for to in ELIST[x]: if USE[to]==1: continue NQ.append(to) ANS2*=score Q=NQ #print(ANS2) Q=deque() for j in ELIST[MID]: Q.append(j) Q.append(MID) USE=[0]*(N+1) USE[j]=1 USE[MID]=1 score2=1 while Q: NQ=deque() score=1 while Q: x=Q.pop() USE[x]=1 #if x!=MID and x!=j: score=max(score,len(ELIST[x])-1) for to in ELIST[x]: if USE[to]==1: continue NQ.append(to) #print("!",x,score) score2*=score Q=NQ #print(j,score2) ANS2=min(ANS2,score2*2) print(ANS2) ```
output
1
71,461
13
142,923
Provide a correct Python 3 solution for this coding contest problem. Coloring of the vertices of a tree G is called a good coloring when, for every pair of two vertices u and v painted in the same color, picking u as the root and picking v as the root would result in isomorphic rooted trees. Also, the colorfulness of G is defined as the minimum possible number of different colors used in a good coloring of G. You are given a tree with N vertices. The vertices are numbered 1 through N, and the i-th edge connects Vertex a_i and Vertex b_i. We will construct a new tree T by repeating the following operation on this tree some number of times: * Add a new vertex to the tree by connecting it to one of the vertices in the current tree with an edge. Find the minimum possible colorfulness of T. Additionally, print the minimum number of leaves (vertices with degree 1) in a tree T that achieves the minimum colorfulness. Constraints * 2 \leq N \leq 100 * 1 \leq a_i,b_i \leq N(1\leq i\leq N-1) * The given graph is a tree. Input Input is given from Standard Input in the following format: N a_1 b_1 : a_{N-1} b_{N-1} Output Print two integers with a space in between. First, print the minimum possible colorfulness of a tree T that can be constructed. Second, print the minimum number of leaves in a tree that achieves it. It can be shown that, under the constraints of this problem, the values that should be printed fit into 64-bit signed integers. Examples Input 5 1 2 2 3 3 4 3 5 Output 2 4 Input 8 1 2 2 3 4 3 5 4 6 7 6 8 3 6 Output 3 4 Input 10 1 2 2 3 3 4 4 5 5 6 6 7 3 8 5 9 3 10 Output 4 6 Input 13 5 6 6 4 2 8 4 7 8 9 3 2 10 4 11 10 2 4 13 10 1 8 12 1 Output 4 12
instruction
0
71,462
13
142,924
"Correct Solution: ``` n = int(input()) sus = [[] for i in range(n)] edges = [] for i in range(n - 1): a, b = map(int, input().split()) a -= 1 b -= 1 sus[a].append(b) sus[b].append(a) edges.append((a, b)) def probaj(korijen): bio = [False for i in range(n)] maks = [0 for i in range(n)] def dfs(x, level): nonlocal bio nonlocal maks bio[x] = True djece = 0 for y in sus[x]: if not bio[y]: dfs(y, level + 1) djece += 1 maks[level] = max(maks[level], djece) if isinstance(korijen, tuple): k1, k2 = korijen bio[k1] = bio[k2] = True dfs(k1, 0) dfs(k2, 0) a, b = 1, 2 else: dfs(korijen, 0) a, b = 1, 1 for l in range(n): if maks[l]: b *= maks[l] a += 1 else: break return a, b p1 = min(probaj(i) for i in range(n)) p2 = min(probaj(e) for e in edges) p = min(p1, p2) print(p[0], p[1]) ```
output
1
71,462
13
142,925
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Coloring of the vertices of a tree G is called a good coloring when, for every pair of two vertices u and v painted in the same color, picking u as the root and picking v as the root would result in isomorphic rooted trees. Also, the colorfulness of G is defined as the minimum possible number of different colors used in a good coloring of G. You are given a tree with N vertices. The vertices are numbered 1 through N, and the i-th edge connects Vertex a_i and Vertex b_i. We will construct a new tree T by repeating the following operation on this tree some number of times: * Add a new vertex to the tree by connecting it to one of the vertices in the current tree with an edge. Find the minimum possible colorfulness of T. Additionally, print the minimum number of leaves (vertices with degree 1) in a tree T that achieves the minimum colorfulness. Constraints * 2 \leq N \leq 100 * 1 \leq a_i,b_i \leq N(1\leq i\leq N-1) * The given graph is a tree. Input Input is given from Standard Input in the following format: N a_1 b_1 : a_{N-1} b_{N-1} Output Print two integers with a space in between. First, print the minimum possible colorfulness of a tree T that can be constructed. Second, print the minimum number of leaves in a tree that achieves it. It can be shown that, under the constraints of this problem, the values that should be printed fit into 64-bit signed integers. Examples Input 5 1 2 2 3 3 4 3 5 Output 2 4 Input 8 1 2 2 3 4 3 5 4 6 7 6 8 3 6 Output 3 4 Input 10 1 2 2 3 3 4 4 5 5 6 6 7 3 8 5 9 3 10 Output 4 6 Input 13 5 6 6 4 2 8 4 7 8 9 3 2 10 4 11 10 2 4 13 10 1 8 12 1 Output 4 12 Submitted Solution: ``` from collections import deque def f(n, dm, g, ind, a, b): q = deque([a, b]) d = [-1] * n d[a] = 0 d[b] = 0 while q: p = q.popleft() for node in g[p]: if d[node] == -1: d[node] = d[p] + 1 q.append(node) l = [0] * (dm // 2 + 1) if a == b: l[0] = ind[a] for i in range(n): l[d[i]] = max(l[d[i]], ind[i] - 1) res = 1 for x in l[:-1]: res *= x return res n = int(input()) g = [[] for _ in range(n)] ind = [0] * n for i in range(n - 1): a, b = map(int, input().split()) g[a - 1].append(b - 1) ind[a - 1] += 1 g[b - 1].append(a - 1) ind[b - 1] += 1 s = [0] d = [-1] * n d[0] = 0 while s: p = s.pop() for node in g[p]: if d[node] == -1: d[node] = d[p] + 1 s.append(node) m = max(d) idx = d.index(m) s = [idx] d1 = [-1] * n d1[idx] = 0 while s: p = s.pop() for node in g[p]: if d1[node] == -1: d1[node] = d1[p] + 1 s.append(node) diam = max(d1) idx = d1.index(diam) s = [idx] d2 = [-1] * n d2[idx] = 0 while s: p = s.pop() for node in g[p]: if d2[node] == -1: d2[node] = d2[p] + 1 s.append(node) if diam & 1: # 直径が奇数 c = [] t = diam // 2 + 1 print(t, end=' ') for i in range(n): if d1[i] <= t and d2[i] <= t: c.append(i) ans = f(n, diam, g, ind, c[0], c[1]) * 2 print(ans) else: t = diam // 2 print(t + 1, end=' ') for i in range(n): if d1[i] <= t and d2[i] <= t: c = i ans = f(n, diam, g, ind, c, c) for node in g[c]: ans = min(ans, f(n, diam, g, ind, c, node) * 2) print(ans) ```
instruction
0
71,463
13
142,926
Yes
output
1
71,463
13
142,927
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Coloring of the vertices of a tree G is called a good coloring when, for every pair of two vertices u and v painted in the same color, picking u as the root and picking v as the root would result in isomorphic rooted trees. Also, the colorfulness of G is defined as the minimum possible number of different colors used in a good coloring of G. You are given a tree with N vertices. The vertices are numbered 1 through N, and the i-th edge connects Vertex a_i and Vertex b_i. We will construct a new tree T by repeating the following operation on this tree some number of times: * Add a new vertex to the tree by connecting it to one of the vertices in the current tree with an edge. Find the minimum possible colorfulness of T. Additionally, print the minimum number of leaves (vertices with degree 1) in a tree T that achieves the minimum colorfulness. Constraints * 2 \leq N \leq 100 * 1 \leq a_i,b_i \leq N(1\leq i\leq N-1) * The given graph is a tree. Input Input is given from Standard Input in the following format: N a_1 b_1 : a_{N-1} b_{N-1} Output Print two integers with a space in between. First, print the minimum possible colorfulness of a tree T that can be constructed. Second, print the minimum number of leaves in a tree that achieves it. It can be shown that, under the constraints of this problem, the values that should be printed fit into 64-bit signed integers. Examples Input 5 1 2 2 3 3 4 3 5 Output 2 4 Input 8 1 2 2 3 4 3 5 4 6 7 6 8 3 6 Output 3 4 Input 10 1 2 2 3 3 4 4 5 5 6 6 7 3 8 5 9 3 10 Output 4 6 Input 13 5 6 6 4 2 8 4 7 8 9 3 2 10 4 11 10 2 4 13 10 1 8 12 1 Output 4 12 Submitted Solution: ``` import sys input = sys.stdin.readline INF = (1<<60) N = int(input()) graph = [[] for _ in range(N)] Edges = [] for _ in range(N-1): a, b = map(int, input().split()) graph[a-1].append(b-1) graph[b-1].append(a-1) Edges.append((a-1, b-1)) def bfs(s, noback): q = [s] D = [-1]*N D[s] = 0 while q: qq = [] for p in q: for np in graph[p]: if D[np] == -1 and np != noback: D[np] = D[p] + 1 qq.append(np) q = qq Ds = [0]*(N+1) faraway = 0 for i, d in enumerate(D): faraway = max(faraway, d) Ds[d] = max(Ds[d], len(graph[i])-1) return Ds, faraway colorful = INF nodes = INF for n in range(N): M = [0]*(N+1) far = 0 leaves = 0 for s in graph[n]: leaves += 1 Ds, faraway = bfs(s, n) far = max(far, faraway) for i, d in enumerate(Ds): M[i] = max(M[i], d) color = far + 2 if color <= colorful: if color != colorful: nodes = INF colorful = color for f in range(far): leaves *= M[f] if leaves < nodes: nodes = leaves for a, b in Edges: M = [0]*(N+1) leaves = 2 D1, faraway1 = bfs(a, b) for i, d in enumerate(D1): M[i] = max(M[i], d) D2, faraway2 = bfs(b, a) for i, d in enumerate(D2): M[i] = max(M[i], d) far = max(faraway1, faraway2) color = far + 1 if color <= colorful: if color != colorful: nodes = INF colorful = color for f in range(far): leaves *= M[f] if leaves < nodes: nodes = leaves print(colorful, nodes) ```
instruction
0
71,464
13
142,928
Yes
output
1
71,464
13
142,929
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Coloring of the vertices of a tree G is called a good coloring when, for every pair of two vertices u and v painted in the same color, picking u as the root and picking v as the root would result in isomorphic rooted trees. Also, the colorfulness of G is defined as the minimum possible number of different colors used in a good coloring of G. You are given a tree with N vertices. The vertices are numbered 1 through N, and the i-th edge connects Vertex a_i and Vertex b_i. We will construct a new tree T by repeating the following operation on this tree some number of times: * Add a new vertex to the tree by connecting it to one of the vertices in the current tree with an edge. Find the minimum possible colorfulness of T. Additionally, print the minimum number of leaves (vertices with degree 1) in a tree T that achieves the minimum colorfulness. Constraints * 2 \leq N \leq 100 * 1 \leq a_i,b_i \leq N(1\leq i\leq N-1) * The given graph is a tree. Input Input is given from Standard Input in the following format: N a_1 b_1 : a_{N-1} b_{N-1} Output Print two integers with a space in between. First, print the minimum possible colorfulness of a tree T that can be constructed. Second, print the minimum number of leaves in a tree that achieves it. It can be shown that, under the constraints of this problem, the values that should be printed fit into 64-bit signed integers. Examples Input 5 1 2 2 3 3 4 3 5 Output 2 4 Input 8 1 2 2 3 4 3 5 4 6 7 6 8 3 6 Output 3 4 Input 10 1 2 2 3 3 4 4 5 5 6 6 7 3 8 5 9 3 10 Output 4 6 Input 13 5 6 6 4 2 8 4 7 8 9 3 2 10 4 11 10 2 4 13 10 1 8 12 1 Output 4 12 Submitted Solution: ``` N = int(input()) G = [[] for i in range(N)] for i in range(N-1): a, b = map(int, input().split()) G[a-1].append(b-1) G[b-1].append(a-1) from collections import deque def bfs(v): que = deque([v]) dist = {v: 0} prev = {v: v} while que: u = que.popleft() d = dist[u] for w in G[u]: if w in dist: continue dist[w] = d + 1 prev[w] = u que.append(w) w = u D = [] while w != v: D.append(w) w = prev[w] D.append(v) return u, D from collections import deque def solve(u, v = -1): que = deque([u]) if v != -1: que.append(v) used = set([u, v]) D = {v: 0, u: 0} E = {} if v != -1: E[0] = max(len(G[v]), len(G[u]))-1 else: E[0] = len(G[u]) x = v while que: v = que.popleft() d = D[v] for w in G[v]: if w in used: continue D[w] = d + 1 que.append(w) used.add(w) E[d+1] = max(E.get(d+1, 0), len(G[w])-1) res = 2 if x != -1 else 1 for v in E.values(): if v: res *= v return res D = bfs(bfs(0)[0])[1] L = len(D) col = (L + 1) // 2 if L % 2 == 1: ans = 10**18 v = D[L//2] for w in G[v]: ans = min(ans, solve(v, w)) ans = min(ans, solve(v)) else: v = D[L//2-1]; w = D[L//2] ans = solve(v, w) print(col, ans) ```
instruction
0
71,465
13
142,930
Yes
output
1
71,465
13
142,931
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Coloring of the vertices of a tree G is called a good coloring when, for every pair of two vertices u and v painted in the same color, picking u as the root and picking v as the root would result in isomorphic rooted trees. Also, the colorfulness of G is defined as the minimum possible number of different colors used in a good coloring of G. You are given a tree with N vertices. The vertices are numbered 1 through N, and the i-th edge connects Vertex a_i and Vertex b_i. We will construct a new tree T by repeating the following operation on this tree some number of times: * Add a new vertex to the tree by connecting it to one of the vertices in the current tree with an edge. Find the minimum possible colorfulness of T. Additionally, print the minimum number of leaves (vertices with degree 1) in a tree T that achieves the minimum colorfulness. Constraints * 2 \leq N \leq 100 * 1 \leq a_i,b_i \leq N(1\leq i\leq N-1) * The given graph is a tree. Input Input is given from Standard Input in the following format: N a_1 b_1 : a_{N-1} b_{N-1} Output Print two integers with a space in between. First, print the minimum possible colorfulness of a tree T that can be constructed. Second, print the minimum number of leaves in a tree that achieves it. It can be shown that, under the constraints of this problem, the values that should be printed fit into 64-bit signed integers. Examples Input 5 1 2 2 3 3 4 3 5 Output 2 4 Input 8 1 2 2 3 4 3 5 4 6 7 6 8 3 6 Output 3 4 Input 10 1 2 2 3 3 4 4 5 5 6 6 7 3 8 5 9 3 10 Output 4 6 Input 13 5 6 6 4 2 8 4 7 8 9 3 2 10 4 11 10 2 4 13 10 1 8 12 1 Output 4 12 Submitted Solution: ``` from collections import deque from functools import reduce from itertools import zip_longest from operator import mul def dfs(links): q = deque([(v, 0) for v in links[0]]) v = 0 while q: v, a = q.popleft() q.extend((u, v) for u in links[v] if u != a) anc = [-1] * len(links) q = deque([(u, v) for u in links[v]]) u = 0, 0 while q: u, a = q.popleft() anc[u] = a q.extend((w, u) for w in links[u] if w != a) path = [u] a = u while a != v: a = anc[a] path.append(a) return path def calc(links, v, a, l): ans = [1] * l q = deque([(u, v, 1) for u in links[v] if u != a]) ans[0] = len(q) while q: u, a, c = q.popleft() ans[c] = max(ans[c], len(links[u]) - 1) q.extend((w, u, c + 1) for w in links[u] if w != a) return ans def solve(n, links): if n == 2: return 1, 2 path = dfs(links) c = len(path) l = (len(path) + 1) // 2 # print('path', path) if c % 2 == 0: u, v = path[c // 2 - 1], path[c // 2] ans1 = calc(links, u, v, l) ans2 = calc(links, v, u, l) # print('ans12', ans1, ans2) leaves = 1 for a1, a2 in zip(ans1, ans2): leaves *= max(a1, a2) return len(ans1), leaves * 2 v = path[c // 2] ans0 = calc(links, v, None, l) leaves = reduce(mul, ans0, 1) # print('ans0', ans0, leaves) for u in links[v]: ans1 = calc(links, u, v, l) ans2 = calc(links, v, u, l) tmp = 1 for a1, a2 in zip_longest(ans1, ans2): tmp *= max(a1, a2) # print('ans12', ans1, ans2, tmp) leaves = min(leaves, tmp * 2) return len(ans0), leaves n = int(input()) links = [set() for _ in range(n)] for _ in range(n - 1): a, b = map(int, input().split()) a -= 1 b -= 1 links[a].add(b) links[b].add(a) print(*solve(n, links)) ```
instruction
0
71,466
13
142,932
Yes
output
1
71,466
13
142,933
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Coloring of the vertices of a tree G is called a good coloring when, for every pair of two vertices u and v painted in the same color, picking u as the root and picking v as the root would result in isomorphic rooted trees. Also, the colorfulness of G is defined as the minimum possible number of different colors used in a good coloring of G. You are given a tree with N vertices. The vertices are numbered 1 through N, and the i-th edge connects Vertex a_i and Vertex b_i. We will construct a new tree T by repeating the following operation on this tree some number of times: * Add a new vertex to the tree by connecting it to one of the vertices in the current tree with an edge. Find the minimum possible colorfulness of T. Additionally, print the minimum number of leaves (vertices with degree 1) in a tree T that achieves the minimum colorfulness. Constraints * 2 \leq N \leq 100 * 1 \leq a_i,b_i \leq N(1\leq i\leq N-1) * The given graph is a tree. Input Input is given from Standard Input in the following format: N a_1 b_1 : a_{N-1} b_{N-1} Output Print two integers with a space in between. First, print the minimum possible colorfulness of a tree T that can be constructed. Second, print the minimum number of leaves in a tree that achieves it. It can be shown that, under the constraints of this problem, the values that should be printed fit into 64-bit signed integers. Examples Input 5 1 2 2 3 3 4 3 5 Output 2 4 Input 8 1 2 2 3 4 3 5 4 6 7 6 8 3 6 Output 3 4 Input 10 1 2 2 3 3 4 4 5 5 6 6 7 3 8 5 9 3 10 Output 4 6 Input 13 5 6 6 4 2 8 4 7 8 9 3 2 10 4 11 10 2 4 13 10 1 8 12 1 Output 4 12 Submitted Solution: ``` import sys readline = sys.stdin.readline inf = 10**9+7 def dfs(s, Edge): dist = [inf]*N dist[s] = 0 stack = [s] used = set([s]) while stack: vn = stack.pop() for vf in Edge[vn]: if vf not in used: used.add(vf) dist[vf] = 1+dist[vn] stack.append(vf) return dist def calc(v1, v2, Dim): d1 = dfs(v1, Edge) d2 = dfs(v2, Edge) di1 = [0]*N di2 = [0]*N for i in range(N): if d1[i] < d2[i]: di1[d1[i]] = max(di1[d1[i]], Dim[i] - 1) else: di2[d2[i]] = max(di2[d2[i]], Dim[i] - 1) K = [max(f1, f2) for f1, f2 in zip(di1, di2)] res = 1 for k in K: if not k: continue res = res*k return 2*res N = int(readline()) Edge = [[] for _ in range(N)] Dim = [0]*N for _ in range(N-1): a, b = map(int, readline().split()) a -= 1 b -= 1 Edge[a].append(b) Edge[b].append(a) Dim[a] += 1 Dim[b] += 1 dist0 = dfs(0, Edge) vfst = dist0.index(max(dist0)) dist1 = dfs(vfst, Edge) D = max(dist1) ans = inf if D&1: C1 = [i for i in range(N) if dist1[i] == D//2] C2 = [i for i in range(N) if dist1[i] == D//2+1] for c1 in C1: for c2 in C2: ans = min(ans, calc(c1, c2, Dim)) else: c = dist1.index(D//2) dic = [0]*N dic[0] = Dim[c] dc = dfs(c, Edge) for i in range(N): dic[dc[i]] = max(dic[dc[i]],Dim[i]-1) ans = 1 for i in range(N): if dic[i]: ans = ans*dic[i] for vc in Edge[c]: ans = min(ans, calc(vc, c, Dim)) print(-(-(D+1)//2), ans) ```
instruction
0
71,467
13
142,934
No
output
1
71,467
13
142,935
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Coloring of the vertices of a tree G is called a good coloring when, for every pair of two vertices u and v painted in the same color, picking u as the root and picking v as the root would result in isomorphic rooted trees. Also, the colorfulness of G is defined as the minimum possible number of different colors used in a good coloring of G. You are given a tree with N vertices. The vertices are numbered 1 through N, and the i-th edge connects Vertex a_i and Vertex b_i. We will construct a new tree T by repeating the following operation on this tree some number of times: * Add a new vertex to the tree by connecting it to one of the vertices in the current tree with an edge. Find the minimum possible colorfulness of T. Additionally, print the minimum number of leaves (vertices with degree 1) in a tree T that achieves the minimum colorfulness. Constraints * 2 \leq N \leq 100 * 1 \leq a_i,b_i \leq N(1\leq i\leq N-1) * The given graph is a tree. Input Input is given from Standard Input in the following format: N a_1 b_1 : a_{N-1} b_{N-1} Output Print two integers with a space in between. First, print the minimum possible colorfulness of a tree T that can be constructed. Second, print the minimum number of leaves in a tree that achieves it. It can be shown that, under the constraints of this problem, the values that should be printed fit into 64-bit signed integers. Examples Input 5 1 2 2 3 3 4 3 5 Output 2 4 Input 8 1 2 2 3 4 3 5 4 6 7 6 8 3 6 Output 3 4 Input 10 1 2 2 3 3 4 4 5 5 6 6 7 3 8 5 9 3 10 Output 4 6 Input 13 5 6 6 4 2 8 4 7 8 9 3 2 10 4 11 10 2 4 13 10 1 8 12 1 Output 4 12 Submitted Solution: ``` import sys readline = sys.stdin.readline inf = 10**9+7 def dfs(s, Edge): dist = [inf]*N dist[s] = 0 stack = [s] used = set([s]) while stack: vn = stack.pop() for vf in Edge[vn]: if vf not in used: used.add(vf) dist[vf] = 1+dist[vn] stack.append(vf) return dist def calc(v1, v2, Dim): d1 = dfs(v1, Edge) d2 = dfs(v2, Edge) di1 = [0]*N di2 = [0]*N for i in range(N): if d1[i] < d2[i]: di1[d1[i]] = max(di1[d1[i]], Dim[i] - 1) else: di2[d2[i]] = max(di2[d2[i]], Dim[i] - 1) K = [max(f1, f2) for f1, f2 in zip(di1, di2)] res = 1 for k in K: if not k: continue res = res*k return 2*res N = int(readline()) Edge = [[] for _ in range(N)] Dim = [0]*N for _ in range(N-1): a, b = map(int, readline().split()) a -= 1 b -= 1 Edge[a].append(b) Edge[b].append(a) Dim[a] += 1 Dim[b] += 1 dist0 = dfs(0, Edge) vfst = dist0.index(max(dist0)) dist1 = dfs(vfst, Edge) D = max(dist1) ans = inf if D&1: C1 = [i for i in range(N) if dist1[i] == D//2] C2 = [i for i in range(N) if dist1[i] == D//2+1] for c1 in C1: for c2 in C2: ans = calc(c1, c2, Dim) else: c = dist1.index(D//2) dic = [0]*N dic[0] = Dim[c] dc = dfs(c, Edge) for i in range(N): dic[dc[i]] = max(dic[dc[i]],Dim[i]-1) ans = 1 for i in range(N): if dic[i]: ans = ans*dic[i] for vc in Edge[c]: ans = min(ans, calc(vc, c, Dim)) print(-(-(D+1)//2), ans) ```
instruction
0
71,468
13
142,936
No
output
1
71,468
13
142,937
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Coloring of the vertices of a tree G is called a good coloring when, for every pair of two vertices u and v painted in the same color, picking u as the root and picking v as the root would result in isomorphic rooted trees. Also, the colorfulness of G is defined as the minimum possible number of different colors used in a good coloring of G. You are given a tree with N vertices. The vertices are numbered 1 through N, and the i-th edge connects Vertex a_i and Vertex b_i. We will construct a new tree T by repeating the following operation on this tree some number of times: * Add a new vertex to the tree by connecting it to one of the vertices in the current tree with an edge. Find the minimum possible colorfulness of T. Additionally, print the minimum number of leaves (vertices with degree 1) in a tree T that achieves the minimum colorfulness. Constraints * 2 \leq N \leq 100 * 1 \leq a_i,b_i \leq N(1\leq i\leq N-1) * The given graph is a tree. Input Input is given from Standard Input in the following format: N a_1 b_1 : a_{N-1} b_{N-1} Output Print two integers with a space in between. First, print the minimum possible colorfulness of a tree T that can be constructed. Second, print the minimum number of leaves in a tree that achieves it. It can be shown that, under the constraints of this problem, the values that should be printed fit into 64-bit signed integers. Examples Input 5 1 2 2 3 3 4 3 5 Output 2 4 Input 8 1 2 2 3 4 3 5 4 6 7 6 8 3 6 Output 3 4 Input 10 1 2 2 3 3 4 4 5 5 6 6 7 3 8 5 9 3 10 Output 4 6 Input 13 5 6 6 4 2 8 4 7 8 9 3 2 10 4 11 10 2 4 13 10 1 8 12 1 Output 4 12 Submitted Solution: ``` from collections import defaultdict, deque, Counter from heapq import heappush, heappop, heapify import bisect import random from itertools import permutations, accumulate, combinations, product import sys import string from bisect import bisect_left, bisect_right from math import factorial, ceil, floor, gcd, sqrt from operator import mul from functools import reduce from operator import mul from pprint import pprint sys.setrecursionlimit(2147483647) INF = 10 ** 20 def LI(): return list(map(int, sys.stdin.buffer.readline().split())) def I(): return int(sys.stdin.buffer.readline()) def LS(): return sys.stdin.buffer.readline().rstrip().decode('utf-8').split() def S(): return sys.stdin.buffer.readline().rstrip().decode('utf-8') def IR(n): return [I() for i in range(n)] def LIR(n): return [LI() for i in range(n)] def SR(n): return [S() for i in range(n)] def LSR(n): return [LS() for i in range(n)] def SRL(n): return [list(S()) for i in range(n)] def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)] mod = 1000000007 n = I() G = [[] for _ in range(n)] for a, b in LIR(n - 1): G[a - 1] += [b - 1] G[b - 1] += [a - 1] def bfs(G, s=0): que = deque([s]) # n = len(G) dist = [INF] * n par = [-1] * n dist[s] = 0 while que: u = que.popleft() for v in G[u]: if par[u] != v: dist[v] = dist[u] + 1 que += [v] par[v] = u return dist, par dist, _ = bfs(G, s=0) # n = len(G) ret = -1 for u in range(n): if dist[u] > ret: ret = dist[u] v = u dist2, par = bfs(G, s=v) # 直径の長さだけを知りたい時は、return max(dist) diameter = -1 for i in range(n): if dist2[i] > diameter: diameter = dist2[i] w = i L = [0] * (diameter + 1) now = w L[0] = w for i in range(diameter): now = par[now] L[i + 1] = now visited = [0] * n q = [L[diameter // 2]] visited[L[diameter // 2]] = 1 if diameter % 2: q += [L[diameter // 2 + 1]] visited[L[diameter // 2 + 1]] = 1 cnt = 2 if diameter % 2 else 1 for k in range(diameter // 2): qq = [] max_deg = 0 for ii in q: if k == 0 and diameter % 2 == 0: max_deg = len(G[ii]) else: max_deg = max(max_deg, len(G[ii]) - 1) for vv in G[ii]: if visited[vv]: continue visited[vv] = 1 qq += [vv] cnt = cnt * max_deg q = qq print(diameter // 2 + 1, cnt) ```
instruction
0
71,469
13
142,938
No
output
1
71,469
13
142,939
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Coloring of the vertices of a tree G is called a good coloring when, for every pair of two vertices u and v painted in the same color, picking u as the root and picking v as the root would result in isomorphic rooted trees. Also, the colorfulness of G is defined as the minimum possible number of different colors used in a good coloring of G. You are given a tree with N vertices. The vertices are numbered 1 through N, and the i-th edge connects Vertex a_i and Vertex b_i. We will construct a new tree T by repeating the following operation on this tree some number of times: * Add a new vertex to the tree by connecting it to one of the vertices in the current tree with an edge. Find the minimum possible colorfulness of T. Additionally, print the minimum number of leaves (vertices with degree 1) in a tree T that achieves the minimum colorfulness. Constraints * 2 \leq N \leq 100 * 1 \leq a_i,b_i \leq N(1\leq i\leq N-1) * The given graph is a tree. Input Input is given from Standard Input in the following format: N a_1 b_1 : a_{N-1} b_{N-1} Output Print two integers with a space in between. First, print the minimum possible colorfulness of a tree T that can be constructed. Second, print the minimum number of leaves in a tree that achieves it. It can be shown that, under the constraints of this problem, the values that should be printed fit into 64-bit signed integers. Examples Input 5 1 2 2 3 3 4 3 5 Output 2 4 Input 8 1 2 2 3 4 3 5 4 6 7 6 8 3 6 Output 3 4 Input 10 1 2 2 3 3 4 4 5 5 6 6 7 3 8 5 9 3 10 Output 4 6 Input 13 5 6 6 4 2 8 4 7 8 9 3 2 10 4 11 10 2 4 13 10 1 8 12 1 Output 4 12 Submitted Solution: ``` from collections import deque from functools import reduce from itertools import zip_longest from operator import mul def dfs(links): q = deque([(v, 0) for v in links[0]]) v = 0 while q: v, a = q.popleft() q.extend((u, v) for u in links[v] if u != a) anc = [-1] * len(links) q = deque([(u, v) for u in links[v]]) u = 0, 0 while q: u, a = q.popleft() anc[u] = a q.extend((w, u) for w in links[u] if w != a) path = [u] a = u while a != v: a = anc[a] path.append(a) return path def calc(links, v, a, l): ans = [1] * l q = deque([(u, v, 1) for u in links[v] if u != a]) ans[0] = len(q) while q: u, a, c = q.popleft() ans[c] = max(ans[c], len(links[u]) - 1) q.extend((w, u, c + 1) for w in links[u] if w != a) return ans def solve(n, links): if n == 2: return 1, 0 path = dfs(links) c = len(path) l = (len(path) + 1) // 2 # print('path', path) if c % 2 == 0: u, v = path[c // 2 - 1], path[c // 2] ans1 = calc(links, u, v, l) ans2 = calc(links, v, u, l) # print('ans12', ans1, ans2) leaves = 1 for a1, a2 in zip(ans1, ans2): leaves *= max(a1, a2) return len(ans1), leaves * 2 v = path[c // 2] ans0 = calc(links, v, None, l) leaves = reduce(mul, ans0, 1) # print('ans0', ans0, leaves) for u in links[v]: ans1 = calc(links, u, v, l) ans2 = calc(links, v, u, l) tmp = 1 for a1, a2 in zip_longest(ans1, ans2): tmp *= max(a1, a2) # print('ans12', ans1, ans2, tmp) leaves = min(leaves, tmp * 2) return len(ans0), leaves n = int(input()) links = [set() for _ in range(n)] for _ in range(n - 1): a, b = map(int, input().split()) a -= 1 b -= 1 links[a].add(b) links[b].add(a) print(*solve(n, links)) ```
instruction
0
71,470
13
142,940
No
output
1
71,470
13
142,941
Provide a correct Python 3 solution for this coding contest problem. You are given an undirected graph G. G has N vertices and M edges. The vertices are numbered from 1 through N, and the i-th edge (1 ≤ i ≤ M) connects Vertex a_i and b_i. G does not have self-loops and multiple edges. You can repeatedly perform the operation of adding an edge between two vertices. However, G must not have self-loops or multiple edges as the result. Also, if Vertex 1 and 2 are connected directly or indirectly by edges, your body will be exposed to a voltage of 1000000007 volts. This must also be avoided. Under these conditions, at most how many edges can you add? Note that Vertex 1 and 2 are never connected directly or indirectly in the beginning. Constraints * 2 ≤ N ≤ 10^5 * 0 ≤ M ≤ 10^5 * 1 ≤ a_i < b_i ≤ N * All pairs (a_i, b_i) are distinct. * Vertex 1 and 2 in G are not connected directly or indirectly by edges. Input Input is given from Standard Input in the following format: N M a_1 b_1 : a_M b_M Output Print the maximum number of edges that can be added. Examples Input 4 1 1 3 Output 2 Input 2 0 Output 0 Input 9 6 1 4 1 8 2 5 3 6 4 8 5 7 Output 12
instruction
0
71,471
13
142,942
"Correct Solution: ``` from heapq import heappush,heappop,heapify from collections import deque,defaultdict,Counter import itertools from functools import * from itertools import permutations,combinations,groupby import sys import bisect import string import math import time import random def Golf(): *a,=map(int,open(0)) def S_(): return input() def IS(): return input().split() def LS(): return [i for i in input().split()] def I(): return int(input()) def MI(): return map(int,input().split()) def LI(): return [int(i) for i in input().split()] def LI_(): return [int(i)-1 for i in input().split()] def NI(n): return [int(input()) for i in range(n)] def NI_(n): return [int(input())-1 for i in range(n)] def StoI(): return [ord(i)-97 for i in input()] def ItoS(nn): return chr(nn+97) def LtoS(ls): return ''.join([chr(i+97) for i in ls]) def GI(V,E,Directed=False,index=0): org_inp=[] g=[[] for i in range(n)] for i in range(E): inp=LI() org_inp.append(inp) if index==0: inp[0]-=1 inp[1]-=1 if len(inp)==2: a,b=inp g[a].append(b) if not Directed: g[b].append(a) elif len(inp)==3: a,b,c=inp aa=(inp[0],inp[2]) bb=(inp[1],inp[2]) g[a].append(bb) if not Directed: g[b].append(aa) return g,org_inp def GGI(h,w,search=None,replacement_of_found='.',mp_def={'#':1,'.':0}): #h,w,g,sg=GGI(h,w,search=['S','G'],replacement_of_found='.',mp_def={'#':1,'.':0}) # sample usage mp=[1]*(w+2) found={} for i in range(h): s=input() for char in search: if char in s: found[char]=((i+1)*(w+2)+s.index(char)+1) mp_def[char]=mp_def[replacement_of_found] mp+=[1]+[mp_def[j] for j in s]+[1] mp+=[1]*(w+2) return h+2,w+2,mp,found def bit_combination(k,n=2): rt=[] for tb in range(n**k): s=[tb//(n**bt)%n for bt in range(k)] rt+=[s] return rt def show(*inp,end='\n'): if show_flg: print(*inp,end=end) YN=['YES','NO'] mo=10**9+7 inf=float('inf') l_alp=string.ascii_lowercase u_alp=string.ascii_uppercase ts=time.time() #sys.setrecursionlimit(10**7) input=lambda: sys.stdin.readline().rstrip() def ran_input(): import random n=random.randint(4,16) rmin,rmax=1,10 a=[random.randint(rmin,rmax) for _ in range(n)] return n,a show_flg=False show_flg=True ans=0 n,m=LI() g,c=GI(n,m) def bfs(x): v=[0]*n q=[x] while q: c=q.pop() v[c]=1 for nb in g[c]: if v[nb]==0: q.append(nb) v[nb]=1 return sum(v) x=min(bfs(0),bfs(1)) print(n*(n-1)//2-x*(n-x)-m) ```
output
1
71,471
13
142,943
Provide a correct Python 3 solution for this coding contest problem. You are given an undirected graph G. G has N vertices and M edges. The vertices are numbered from 1 through N, and the i-th edge (1 ≤ i ≤ M) connects Vertex a_i and b_i. G does not have self-loops and multiple edges. You can repeatedly perform the operation of adding an edge between two vertices. However, G must not have self-loops or multiple edges as the result. Also, if Vertex 1 and 2 are connected directly or indirectly by edges, your body will be exposed to a voltage of 1000000007 volts. This must also be avoided. Under these conditions, at most how many edges can you add? Note that Vertex 1 and 2 are never connected directly or indirectly in the beginning. Constraints * 2 ≤ N ≤ 10^5 * 0 ≤ M ≤ 10^5 * 1 ≤ a_i < b_i ≤ N * All pairs (a_i, b_i) are distinct. * Vertex 1 and 2 in G are not connected directly or indirectly by edges. Input Input is given from Standard Input in the following format: N M a_1 b_1 : a_M b_M Output Print the maximum number of edges that can be added. Examples Input 4 1 1 3 Output 2 Input 2 0 Output 0 Input 9 6 1 4 1 8 2 5 3 6 4 8 5 7 Output 12
instruction
0
71,472
13
142,944
"Correct Solution: ``` import sys input = sys.stdin.readline sys.setrecursionlimit(10 ** 9) MOD = 10 ** 9 + 7 class UnionFind(object): def __init__(self, N): self.parent = [-1] * N #parent[i] は(i+1)番目の要素が含まれる要素数の(-1)倍 #要素が負-->その数を親とするグループに属する要素の数×(-1) #要素が正-->親のindex #Aがどのグループに属しているかを調べる def root(self, A): if self.parent[A-1] < 0: #負の数-->その数は親 return A self.parent[A-1] = self.root(self.parent[A-1]) #負では無い時、親の場所が入っているから、親が属しているグループを、自分自身に入れる(一度確認したところは直接親を見れるようにする) return self.parent[A-1] #親の位置を返す #Aが含まれているグループに属している数を返す def size(self, A): return -1 * self.parent[self.root(A)-1] #AとBをくっ付ける def connect(self, A, B): A = self.root(A) #Aを含むグループの親を返す B = self.root(B) #Bを含むグループの親を返す if A == B: #親が同じならなにもしない return False #大きい方(A)に小さい方(B)をつなぎたい if self.size(A) < self.size(B): #大小関係が逆の時は入れ替える A, B = B, A self.parent[A-1] += self.parent[B-1] #大きい方に小さい方を加える (負の数+負の数 = 新しいグループに含まれる数×(-1)) self.parent[B-1] = A #加えられた親の値を、加えた先の親の位置に書き変える return True def same(self, A, B): if self.root(A) == self.root(B): return True else: return False N, M = map(int, input().split()) uni = UnionFind(N) for _ in range(M): a, b = map(int, input().split()) uni.connect(a, b) group1 = uni.size(1) group2 = uni.size(2) other = 0 #どっちとも繋がっていない頂点の数 for i in range(3, N + 1): # print ('親', uni.root(i)) if (uni.same(1, i)): continue if (uni.same(2, i)): continue other += 1 #片方に固めたほうが良い? if group1 < group2: group2 += other else: group1 += other # print (group1, group2) ans = group1 * (group1 - 1) // 2 + group2 * (group2 - 1) // 2 - M print (ans) # print (uni.parent) ```
output
1
71,472
13
142,945
Provide a correct Python 3 solution for this coding contest problem. You are given an undirected graph G. G has N vertices and M edges. The vertices are numbered from 1 through N, and the i-th edge (1 ≤ i ≤ M) connects Vertex a_i and b_i. G does not have self-loops and multiple edges. You can repeatedly perform the operation of adding an edge between two vertices. However, G must not have self-loops or multiple edges as the result. Also, if Vertex 1 and 2 are connected directly or indirectly by edges, your body will be exposed to a voltage of 1000000007 volts. This must also be avoided. Under these conditions, at most how many edges can you add? Note that Vertex 1 and 2 are never connected directly or indirectly in the beginning. Constraints * 2 ≤ N ≤ 10^5 * 0 ≤ M ≤ 10^5 * 1 ≤ a_i < b_i ≤ N * All pairs (a_i, b_i) are distinct. * Vertex 1 and 2 in G are not connected directly or indirectly by edges. Input Input is given from Standard Input in the following format: N M a_1 b_1 : a_M b_M Output Print the maximum number of edges that can be added. Examples Input 4 1 1 3 Output 2 Input 2 0 Output 0 Input 9 6 1 4 1 8 2 5 3 6 4 8 5 7 Output 12
instruction
0
71,473
13
142,946
"Correct Solution: ``` n,m=map(int,input().split()) a=[i for i in range(n+1)] b=[0]*(n+1) def f(x): if a[x]==x: return x x=a[x] return(f(x)) def s(x,y): x=f(x) y=f(y) if x!=y: if b[x]<b[y]: a[x]=y b[y]+=1 else: a[y]=x b[x]+=1 for i in range(m): c,d=map(int,input().split()) s(c,d) for i in range(1,n+1): a[i]=f(i) d=a.count(a[2]) s=a.count(a[1]) print(max(((n-d)*(n-d-1)//2)-m+(d*(d-1)//2),((n-s)*(n-s-1)//2)-m+(s*(s-1)//2))) ```
output
1
71,473
13
142,947
Provide a correct Python 3 solution for this coding contest problem. You are given an undirected graph G. G has N vertices and M edges. The vertices are numbered from 1 through N, and the i-th edge (1 ≤ i ≤ M) connects Vertex a_i and b_i. G does not have self-loops and multiple edges. You can repeatedly perform the operation of adding an edge between two vertices. However, G must not have self-loops or multiple edges as the result. Also, if Vertex 1 and 2 are connected directly or indirectly by edges, your body will be exposed to a voltage of 1000000007 volts. This must also be avoided. Under these conditions, at most how many edges can you add? Note that Vertex 1 and 2 are never connected directly or indirectly in the beginning. Constraints * 2 ≤ N ≤ 10^5 * 0 ≤ M ≤ 10^5 * 1 ≤ a_i < b_i ≤ N * All pairs (a_i, b_i) are distinct. * Vertex 1 and 2 in G are not connected directly or indirectly by edges. Input Input is given from Standard Input in the following format: N M a_1 b_1 : a_M b_M Output Print the maximum number of edges that can be added. Examples Input 4 1 1 3 Output 2 Input 2 0 Output 0 Input 9 6 1 4 1 8 2 5 3 6 4 8 5 7 Output 12
instruction
0
71,474
13
142,948
"Correct Solution: ``` class UnionFindTree(): def __init__(self, N): self.N = N self.__parent_of = [None] * N self.__rank_of = [0] * N self.__size = [1] * N def root(self, value): if self.__parent_of[value] is None: return value else: self.__parent_of[value] = self.root(self.__parent_of[value]) return self.__parent_of[value] def unite(self, a, b): r1 = self.root(a) r2 = self.root(b) if r1 != r2: if self.__rank_of[r1] < self.__rank_of[r2]: self.__parent_of[r1] = r2 self.__size[r2] += self.__size[r1] else: self.__parent_of[r2] = r1 self.__size[r1] += self.__size[r2] if self.__rank_of[r1] == self.__rank_of[r2]: self.__rank_of[r1] += 1 def is_same(self, a, b): return self.root(a) == self.root(b) def size(self, a): return self.__size[self.root(a)] def groups(self): groups = {} for k in range(self.N): r = self.root(k) if r not in groups: groups[r] = [] groups[r].append(k) return [groups[x] for x in groups] def main(): N, M = map(int, input().split()) uft = UnionFindTree(N) for _ in range(M): a, b = map(int, input().split()) uft.unite(a-1, b-1) ans = 0 for g in uft.groups(): if 0 in g or 1 in g: x = len(g) y = N - x ans = max(ans, x * (x-1) // 2 + y * (y-1) // 2 - M) print(ans) if __name__ == "__main__": main() ```
output
1
71,474
13
142,949
Provide a correct Python 3 solution for this coding contest problem. You are given an undirected graph G. G has N vertices and M edges. The vertices are numbered from 1 through N, and the i-th edge (1 ≤ i ≤ M) connects Vertex a_i and b_i. G does not have self-loops and multiple edges. You can repeatedly perform the operation of adding an edge between two vertices. However, G must not have self-loops or multiple edges as the result. Also, if Vertex 1 and 2 are connected directly or indirectly by edges, your body will be exposed to a voltage of 1000000007 volts. This must also be avoided. Under these conditions, at most how many edges can you add? Note that Vertex 1 and 2 are never connected directly or indirectly in the beginning. Constraints * 2 ≤ N ≤ 10^5 * 0 ≤ M ≤ 10^5 * 1 ≤ a_i < b_i ≤ N * All pairs (a_i, b_i) are distinct. * Vertex 1 and 2 in G are not connected directly or indirectly by edges. Input Input is given from Standard Input in the following format: N M a_1 b_1 : a_M b_M Output Print the maximum number of edges that can be added. Examples Input 4 1 1 3 Output 2 Input 2 0 Output 0 Input 9 6 1 4 1 8 2 5 3 6 4 8 5 7 Output 12
instruction
0
71,475
13
142,950
"Correct Solution: ``` from heapq import heappush,heappop,heapify from collections import deque,defaultdict,Counter import itertools from functools import * from itertools import permutations,combinations,groupby import sys import bisect import string import math import time import random def Golf(): *a,=map(int,open(0)) def S_(): return input() def IS(): return input().split() def LS(): return [i for i in input().split()] def I(): return int(input()) def MI(): return map(int,input().split()) def LI(): return [int(i) for i in input().split()] def LI_(): return [int(i)-1 for i in input().split()] def NI(n): return [int(input()) for i in range(n)] def NI_(n): return [int(input())-1 for i in range(n)] def StoI(): return [ord(i)-97 for i in input()] def ItoS(nn): return chr(nn+97) def LtoS(ls): return ''.join([chr(i+97) for i in ls]) def GI(V,E,Directed=False,index=0): org_inp=[] g=[[] for i in range(n)] for i in range(E): inp=LI() org_inp.append(inp) if index==0: inp[0]-=1 inp[1]-=1 if len(inp)==2: a,b=inp g[a].append(b) if not Directed: g[b].append(a) elif len(inp)==3: a,b,c=inp aa=(inp[0],inp[2]) bb=(inp[1],inp[2]) g[a].append(bb) if not Directed: g[b].append(aa) return g,org_inp def GGI(h,w,search=None,replacement_of_found='.',mp_def={'#':1,'.':0}): #h,w,g,sg=GGI(h,w,search=['S','G'],replacement_of_found='.',mp_def={'#':1,'.':0}) # sample usage mp=[1]*(w+2) found={} for i in range(h): s=input() for char in search: if char in s: found[char]=((i+1)*(w+2)+s.index(char)+1) mp_def[char]=mp_def[replacement_of_found] mp+=[1]+[mp_def[j] for j in s]+[1] mp+=[1]*(w+2) return h+2,w+2,mp,found def bit_combination(k,n=2): rt=[] for tb in range(n**k): s=[tb//(n**bt)%n for bt in range(k)] rt+=[s] return rt def show(*inp,end='\n'): if show_flg: print(*inp,end=end) YN=['YES','NO'] mo=10**9+7 inf=float('inf') l_alp=string.ascii_lowercase u_alp=string.ascii_uppercase ts=time.time() #sys.setrecursionlimit(10**7) input=lambda: sys.stdin.readline().rstrip() def ran_input(): import random n=random.randint(4,16) rmin,rmax=1,10 a=[random.randint(rmin,rmax) for _ in range(n)] return n,a show_flg=False show_flg=True ans=0 n,m=LI() g,c=GI(n,m) def bfs(x): v=[0]*n q=[x] while q: c=q.pop() v[c]=1 for nb in g[c]: if v[nb]==0: q.append(nb) v[nb]=1 return sum(v),v x,cx=bfs(0) y,cy=bfs(1) if x<y: cy=[1 if cx[i]==0 else 0 for i in range(n)] nx,ny=x,n-x else: cx=[1 if cy[i]==0 else 0 for i in range(n)] nx,ny=n-y,y for i in range(n): if cx[i]==1: # i belongs to x ans+=nx-1-len(g[i]) else: ans+=ny-1-len(g[i]) print(ans//2) ```
output
1
71,475
13
142,951
Provide a correct Python 3 solution for this coding contest problem. You are given an undirected graph G. G has N vertices and M edges. The vertices are numbered from 1 through N, and the i-th edge (1 ≤ i ≤ M) connects Vertex a_i and b_i. G does not have self-loops and multiple edges. You can repeatedly perform the operation of adding an edge between two vertices. However, G must not have self-loops or multiple edges as the result. Also, if Vertex 1 and 2 are connected directly or indirectly by edges, your body will be exposed to a voltage of 1000000007 volts. This must also be avoided. Under these conditions, at most how many edges can you add? Note that Vertex 1 and 2 are never connected directly or indirectly in the beginning. Constraints * 2 ≤ N ≤ 10^5 * 0 ≤ M ≤ 10^5 * 1 ≤ a_i < b_i ≤ N * All pairs (a_i, b_i) are distinct. * Vertex 1 and 2 in G are not connected directly or indirectly by edges. Input Input is given from Standard Input in the following format: N M a_1 b_1 : a_M b_M Output Print the maximum number of edges that can be added. Examples Input 4 1 1 3 Output 2 Input 2 0 Output 0 Input 9 6 1 4 1 8 2 5 3 6 4 8 5 7 Output 12
instruction
0
71,476
13
142,952
"Correct Solution: ``` def root(x): while p[x]>=0:x=p[x] return x def unite(a,b): a,b=root(a),root(b) if a!=b: if p[a]>p[b]:a,b=b,a p[a]+=p[b] p[b]=a n,m,*t=map(int,open(0).read().split()) p=[-1]*n c=[0]*n for a,b in zip(*[iter(t)]*2): a-=1 b-=1 unite(a,b) c[a]+=1 c[b]+=1 a=root(0),root(1) f=p[a[0]]<p[a[1]] t=[0,0] for i in range(n): j=root(i) if j==a[f]: t[f]+=c[i] else: t[f^1]+=c[i] unite(a[f^1],j) r=0 for i in(0,1): n=-p[root(i)] r+=n*(n-1)-t[i]>>1 print(r) ```
output
1
71,476
13
142,953
Provide a correct Python 3 solution for this coding contest problem. You are given an undirected graph G. G has N vertices and M edges. The vertices are numbered from 1 through N, and the i-th edge (1 ≤ i ≤ M) connects Vertex a_i and b_i. G does not have self-loops and multiple edges. You can repeatedly perform the operation of adding an edge between two vertices. However, G must not have self-loops or multiple edges as the result. Also, if Vertex 1 and 2 are connected directly or indirectly by edges, your body will be exposed to a voltage of 1000000007 volts. This must also be avoided. Under these conditions, at most how many edges can you add? Note that Vertex 1 and 2 are never connected directly or indirectly in the beginning. Constraints * 2 ≤ N ≤ 10^5 * 0 ≤ M ≤ 10^5 * 1 ≤ a_i < b_i ≤ N * All pairs (a_i, b_i) are distinct. * Vertex 1 and 2 in G are not connected directly or indirectly by edges. Input Input is given from Standard Input in the following format: N M a_1 b_1 : a_M b_M Output Print the maximum number of edges that can be added. Examples Input 4 1 1 3 Output 2 Input 2 0 Output 0 Input 9 6 1 4 1 8 2 5 3 6 4 8 5 7 Output 12
instruction
0
71,477
13
142,954
"Correct Solution: ``` def examA(): bit = 41 N, K = LI() A = LI() B = [0]*bit for a in A: for j in range(bit): if a&(1<<j)>0: B[j] += 1 ans = 0 cnt = 0 for i in range(bit)[::-1]: if N-B[i]<=B[i]: ans += (1 << i) * B[i] else: if cnt+(1<<i)>K: ans += (1 << i) * B[i] else: cnt += (1 << i) ans += (1 << i) * (N-B[i]) print(ans) return def examB(): N, K = LI() WP = [LI()for _ in range(N)] l = 0; r = 101 for _ in range(100): now = (l+r)/2 W = [0]*N for i,(w,p) in enumerate(WP): W[i] = w*(p-now) W.sort(reverse=True) if sum(W[:K])>=0: l = now else: r = now ans = l print(ans) return def examC(): class UnionFind(): def __init__(self, n): self.parent = [-1 for _ in range(n)] # 正==子: 根の頂点番号 / 負==根: 連結頂点数 def find(self, x): # 要素xが属するグループの根を返す if self.parent[x] < 0: return x else: self.parent[x] = self.find(self.parent[x]) return self.parent[x] def unite(self, x, y): # 要素xが属するグループと要素yが属するグループとを併合する x, y = self.find(x), self.find(y) if x == y: return False else: if self.size(x) < self.size(y): x, y = y, x self.parent[x] += self.parent[y] self.parent[y] = x def same(self, x, y): # 要素x, yが同じグループに属するかどうかを返す return self.find(x) == self.find(y) def size(self, x): # 要素xが属するグループのサイズ(要素数)を返す x = self.find(x) return -self.parent[x] def is_root(self, x): # 要素の根をリストで返す return self.parent[x] < 0 def roots(self): # すべての根の要素をリストで返す return [i for i, x in enumerate(self.parent) if x < 0] def members(self, x): # 要素xが属するグループに属する要素をリストで返す root = self.find(x) return [i for i in range(self.n) if self.find(i) == root] def group_count(self): # グループの数を返す return len(self.roots()) def all_group_members(self): # {ルート要素: [そのグループに含まれる要素のリスト], ...}の辞書を返す return {r: self.members(r) for r in self.roots()} N, M = LI() Uf = UnionFind(N) for _ in range(M): a, b = LI() a -= 1; b -= 1 Uf.unite(a,b) size = [Uf.size(0),Uf.size(1)] size.sort() rest = N-sum(size) size[1] += rest ans = size[0]*(size[0]-1)//2 + size[1]*(size[1]-1)//2 - M print(ans) return def examD(): ans = 0 print(ans) return import sys,bisect,itertools,heapq,math,random from copy import deepcopy from heapq import heappop,heappush,heapify from collections import Counter,defaultdict,deque read = sys.stdin.buffer.read readline = sys.stdin.buffer.readline readlines = sys.stdin.buffer.readlines def I(): return int(input()) def LI(): return list(map(int,sys.stdin.readline().split())) def LSI(): return list(map(str,sys.stdin.readline().split())) def LS(): return sys.stdin.readline().split() def SI(): return sys.stdin.readline().strip() global mod,mod2,inf,alphabet,_ep mod = 10**9 + 7 mod2 = 998244353 inf = 10**18 _ep = 10**(-12) alphabet = [chr(ord('a') + i) for i in range(26)] sys.setrecursionlimit(10**7) if __name__ == '__main__': examC() """ 142 12 9 1445 0 1 asd dfg hj o o aidn """ ```
output
1
71,477
13
142,955
Provide a correct Python 3 solution for this coding contest problem. You are given an undirected graph G. G has N vertices and M edges. The vertices are numbered from 1 through N, and the i-th edge (1 ≤ i ≤ M) connects Vertex a_i and b_i. G does not have self-loops and multiple edges. You can repeatedly perform the operation of adding an edge between two vertices. However, G must not have self-loops or multiple edges as the result. Also, if Vertex 1 and 2 are connected directly or indirectly by edges, your body will be exposed to a voltage of 1000000007 volts. This must also be avoided. Under these conditions, at most how many edges can you add? Note that Vertex 1 and 2 are never connected directly or indirectly in the beginning. Constraints * 2 ≤ N ≤ 10^5 * 0 ≤ M ≤ 10^5 * 1 ≤ a_i < b_i ≤ N * All pairs (a_i, b_i) are distinct. * Vertex 1 and 2 in G are not connected directly or indirectly by edges. Input Input is given from Standard Input in the following format: N M a_1 b_1 : a_M b_M Output Print the maximum number of edges that can be added. Examples Input 4 1 1 3 Output 2 Input 2 0 Output 0 Input 9 6 1 4 1 8 2 5 3 6 4 8 5 7 Output 12
instruction
0
71,478
13
142,956
"Correct Solution: ``` import sys input=sys.stdin.readline N,M=map(int,input().split()) P=[i for i in range(N+1)] size=[1 for i in range(N+1)] def find(a): if a==P[a]: return a else: return find(P[a]) def union(b,c): B=find(b) C=find(c) if P[B]<P[C]: P[C]=P[B] else: P[B]=P[C] L=[] for i in range(M): a,b=map(int,input().split()) L.append([a,b]) union(a,b) p=[i for i in range(N+1)] for i in range(1,N+1): p[i]=find(i) One=0 Two=0 Other=0 for i in range(1,N+1): if p[i]==2: Two+=1 elif p[i]==1: One+=1 else: Other+=1 if One>Two: One+=Other else: Two+=Other print((One*(One-1)//2)+(Two*(Two-1)//2)- M) ```
output
1
71,478
13
142,957
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an undirected graph G. G has N vertices and M edges. The vertices are numbered from 1 through N, and the i-th edge (1 ≤ i ≤ M) connects Vertex a_i and b_i. G does not have self-loops and multiple edges. You can repeatedly perform the operation of adding an edge between two vertices. However, G must not have self-loops or multiple edges as the result. Also, if Vertex 1 and 2 are connected directly or indirectly by edges, your body will be exposed to a voltage of 1000000007 volts. This must also be avoided. Under these conditions, at most how many edges can you add? Note that Vertex 1 and 2 are never connected directly or indirectly in the beginning. Constraints * 2 ≤ N ≤ 10^5 * 0 ≤ M ≤ 10^5 * 1 ≤ a_i < b_i ≤ N * All pairs (a_i, b_i) are distinct. * Vertex 1 and 2 in G are not connected directly or indirectly by edges. Input Input is given from Standard Input in the following format: N M a_1 b_1 : a_M b_M Output Print the maximum number of edges that can be added. Examples Input 4 1 1 3 Output 2 Input 2 0 Output 0 Input 9 6 1 4 1 8 2 5 3 6 4 8 5 7 Output 12 Submitted Solution: ``` # Atcoder Problem Solving # Shock # Code Fesitival Team Relay class UnionFind(): def __init__(self, n): self.n = n self.parents = [-1] * (n+1) def find(self, x): if self.parents[x] < 0: return x else: self.parents[x] = self.find(self.parents[x]) return self.parents[x] def union(self, x, y): x = self.find(x) y = self.find(y) if x == y: return if self.parents[x] > self.parents[y]: x, y = y, x self.parents[x] += self.parents[y] self.parents[y] = x def size(self, x): return -self.parents[self.find(x)] def same(self, x, y): return self.find(x) == self.find(y) def members(self, x): root = self.find(x) return [i for i in range(self.n) if self.find(i) == root] def roots(self): return [i for i, x in enumerate(self.parents) if x < 0] def group_count(self): return len(self.roots()) def all_group_members(self): return {r: self.members(r) for r in self.roots()} def __str__(self): return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots()) N, M = map(int, input().split()) graph = [] G = UnionFind(N) for i in range(M): a, b = map(int, input().split()) G.union(a, b) A = G.size(1) B = G.size(2) C = N-A-B ans = 0 for i in range(C+1): ans = max(ans, (A+i)*(A+i-1)//2 + (B+C-i)*(B+C-i-1)//2-M) print(ans) ```
instruction
0
71,479
13
142,958
Yes
output
1
71,479
13
142,959