message
stringlengths
2
49.9k
message_type
stringclasses
2 values
message_id
int64
0
1
conversation_id
int64
446
108k
cluster
float64
13
13
__index_level_0__
int64
892
217k
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The clique problem is one of the most well-known NP-complete problems. Under some simplification it can be formulated as follows. Consider an undirected graph G. It is required to find a subset of vertices C of the maximum size such that any two of them are connected by an edge in graph G. Sounds simple, doesn't it? Nobody yet knows an algorithm that finds a solution to this problem in polynomial time of the size of the graph. However, as with many other NP-complete problems, the clique problem is easier if you consider a specific type of a graph. Consider n distinct points on a line. Let the i-th point have the coordinate xi and weight wi. Let's form graph G, whose vertices are these points and edges connect exactly the pairs of points (i, j), such that the distance between them is not less than the sum of their weights, or more formally: |xi - xj| β‰₯ wi + wj. Find the size of the maximum clique in such graph. Input The first line contains the integer n (1 ≀ n ≀ 200 000) β€” the number of points. Each of the next n lines contains two numbers xi, wi (0 ≀ xi ≀ 109, 1 ≀ wi ≀ 109) β€” the coordinate and the weight of a point. All xi are different. Output Print a single number β€” the number of vertexes in the maximum clique of the given graph. Examples Input 4 2 3 3 1 6 1 0 2 Output 3 Note If you happen to know how to solve this problem without using the specific properties of the graph formulated in the problem statement, then you are able to get a prize of one million dollars! The picture for the sample test. <image> Submitted Solution: ``` import sys n = int(input()) ranges = [] for xw in sys.stdin: x, w = map(int, xw.split()) ranges.append((x + w, x - w)) ranges.sort() result = 0 end = - float('inf') for e, b in ranges: if b >= end: result += 1 end = e print(result) ```
instruction
0
95,680
13
191,360
Yes
output
1
95,680
13
191,361
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The clique problem is one of the most well-known NP-complete problems. Under some simplification it can be formulated as follows. Consider an undirected graph G. It is required to find a subset of vertices C of the maximum size such that any two of them are connected by an edge in graph G. Sounds simple, doesn't it? Nobody yet knows an algorithm that finds a solution to this problem in polynomial time of the size of the graph. However, as with many other NP-complete problems, the clique problem is easier if you consider a specific type of a graph. Consider n distinct points on a line. Let the i-th point have the coordinate xi and weight wi. Let's form graph G, whose vertices are these points and edges connect exactly the pairs of points (i, j), such that the distance between them is not less than the sum of their weights, or more formally: |xi - xj| β‰₯ wi + wj. Find the size of the maximum clique in such graph. Input The first line contains the integer n (1 ≀ n ≀ 200 000) β€” the number of points. Each of the next n lines contains two numbers xi, wi (0 ≀ xi ≀ 109, 1 ≀ wi ≀ 109) β€” the coordinate and the weight of a point. All xi are different. Output Print a single number β€” the number of vertexes in the maximum clique of the given graph. Examples Input 4 2 3 3 1 6 1 0 2 Output 3 Note If you happen to know how to solve this problem without using the specific properties of the graph formulated in the problem statement, then you are able to get a prize of one million dollars! The picture for the sample test. <image> Submitted Solution: ``` n = int(input()) ls= [list(map(int, input().split())) for i in range(n)] lsr = [[max(ls[i][0]-ls[i][1], 0), ls[i][0]+ls[i][1]] for i in range(n)] lsr.sort(key=lambda x: x[1]) idx = 0 ans = 0 for l in lsr: if idx <= l[0]: idx = l[1] ans+=1 print(ans) ```
instruction
0
95,681
13
191,362
Yes
output
1
95,681
13
191,363
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The clique problem is one of the most well-known NP-complete problems. Under some simplification it can be formulated as follows. Consider an undirected graph G. It is required to find a subset of vertices C of the maximum size such that any two of them are connected by an edge in graph G. Sounds simple, doesn't it? Nobody yet knows an algorithm that finds a solution to this problem in polynomial time of the size of the graph. However, as with many other NP-complete problems, the clique problem is easier if you consider a specific type of a graph. Consider n distinct points on a line. Let the i-th point have the coordinate xi and weight wi. Let's form graph G, whose vertices are these points and edges connect exactly the pairs of points (i, j), such that the distance between them is not less than the sum of their weights, or more formally: |xi - xj| β‰₯ wi + wj. Find the size of the maximum clique in such graph. Input The first line contains the integer n (1 ≀ n ≀ 200 000) β€” the number of points. Each of the next n lines contains two numbers xi, wi (0 ≀ xi ≀ 109, 1 ≀ wi ≀ 109) β€” the coordinate and the weight of a point. All xi are different. Output Print a single number β€” the number of vertexes in the maximum clique of the given graph. Examples Input 4 2 3 3 1 6 1 0 2 Output 3 Note If you happen to know how to solve this problem without using the specific properties of the graph formulated in the problem statement, then you are able to get a prize of one million dollars! The picture for the sample test. <image> Submitted Solution: ``` MOD = 10 ** 9 + 7 INF = 10 ** 10 import sys sys.setrecursionlimit(100000000) dy = (-1,0,1,0) dx = (0,1,0,-1) def main(): n = int(input()) P = [tuple(map(int,input().split())) for _ in range(n)] P.sort(key = lambda x:sum(x)) ans = 0 X,W = -INF,0 for x,w in P: if abs(x - X) >= W + w: ans += 1 X = x W = w print(ans) if __name__ == '__main__': main() ```
instruction
0
95,682
13
191,364
Yes
output
1
95,682
13
191,365
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The clique problem is one of the most well-known NP-complete problems. Under some simplification it can be formulated as follows. Consider an undirected graph G. It is required to find a subset of vertices C of the maximum size such that any two of them are connected by an edge in graph G. Sounds simple, doesn't it? Nobody yet knows an algorithm that finds a solution to this problem in polynomial time of the size of the graph. However, as with many other NP-complete problems, the clique problem is easier if you consider a specific type of a graph. Consider n distinct points on a line. Let the i-th point have the coordinate xi and weight wi. Let's form graph G, whose vertices are these points and edges connect exactly the pairs of points (i, j), such that the distance between them is not less than the sum of their weights, or more formally: |xi - xj| β‰₯ wi + wj. Find the size of the maximum clique in such graph. Input The first line contains the integer n (1 ≀ n ≀ 200 000) β€” the number of points. Each of the next n lines contains two numbers xi, wi (0 ≀ xi ≀ 109, 1 ≀ wi ≀ 109) β€” the coordinate and the weight of a point. All xi are different. Output Print a single number β€” the number of vertexes in the maximum clique of the given graph. Examples Input 4 2 3 3 1 6 1 0 2 Output 3 Note If you happen to know how to solve this problem without using the specific properties of the graph formulated in the problem statement, then you are able to get a prize of one million dollars! The picture for the sample test. <image> Submitted Solution: ``` # -*- coding: utf-8 -*- """ Created on Fri Feb 15 17:39:24 2019 @author: avina """ n = int(input()) l = [] for _ in range(n): k,m = map(int, input().strip().split()) l.append((k,m)) l.sort(key=lambda x:x[0]) ma = 1 for i in range(n): cou = 1 for j in range(n): if abs(l[i][0] - l[j][0]) >= l[i][1] + l[i][1]: cou+=1 ma = max(cou, ma) print(ma) ```
instruction
0
95,683
13
191,366
No
output
1
95,683
13
191,367
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The clique problem is one of the most well-known NP-complete problems. Under some simplification it can be formulated as follows. Consider an undirected graph G. It is required to find a subset of vertices C of the maximum size such that any two of them are connected by an edge in graph G. Sounds simple, doesn't it? Nobody yet knows an algorithm that finds a solution to this problem in polynomial time of the size of the graph. However, as with many other NP-complete problems, the clique problem is easier if you consider a specific type of a graph. Consider n distinct points on a line. Let the i-th point have the coordinate xi and weight wi. Let's form graph G, whose vertices are these points and edges connect exactly the pairs of points (i, j), such that the distance between them is not less than the sum of their weights, or more formally: |xi - xj| β‰₯ wi + wj. Find the size of the maximum clique in such graph. Input The first line contains the integer n (1 ≀ n ≀ 200 000) β€” the number of points. Each of the next n lines contains two numbers xi, wi (0 ≀ xi ≀ 109, 1 ≀ wi ≀ 109) β€” the coordinate and the weight of a point. All xi are different. Output Print a single number β€” the number of vertexes in the maximum clique of the given graph. Examples Input 4 2 3 3 1 6 1 0 2 Output 3 Note If you happen to know how to solve this problem without using the specific properties of the graph formulated in the problem statement, then you are able to get a prize of one million dollars! The picture for the sample test. <image> Submitted Solution: ``` import io import os input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline n = int(input()) endpoints = [] for x in range(n): p, w = map(int, input().split()) endpoints.append([p-w, p+w]) #bruh endpoints.sort(key=lambda sublist: (-sublist[0], sublist[1])) res = 0 #print(endpoints) bottom = 10**18 * -1 for pt in range(len(endpoints)): if endpoints[pt][0] >= bottom: res += 1 bottom = endpoints[pt][1] print(res) ```
instruction
0
95,684
13
191,368
No
output
1
95,684
13
191,369
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The clique problem is one of the most well-known NP-complete problems. Under some simplification it can be formulated as follows. Consider an undirected graph G. It is required to find a subset of vertices C of the maximum size such that any two of them are connected by an edge in graph G. Sounds simple, doesn't it? Nobody yet knows an algorithm that finds a solution to this problem in polynomial time of the size of the graph. However, as with many other NP-complete problems, the clique problem is easier if you consider a specific type of a graph. Consider n distinct points on a line. Let the i-th point have the coordinate xi and weight wi. Let's form graph G, whose vertices are these points and edges connect exactly the pairs of points (i, j), such that the distance between them is not less than the sum of their weights, or more formally: |xi - xj| β‰₯ wi + wj. Find the size of the maximum clique in such graph. Input The first line contains the integer n (1 ≀ n ≀ 200 000) β€” the number of points. Each of the next n lines contains two numbers xi, wi (0 ≀ xi ≀ 109, 1 ≀ wi ≀ 109) β€” the coordinate and the weight of a point. All xi are different. Output Print a single number β€” the number of vertexes in the maximum clique of the given graph. Examples Input 4 2 3 3 1 6 1 0 2 Output 3 Note If you happen to know how to solve this problem without using the specific properties of the graph formulated in the problem statement, then you are able to get a prize of one million dollars! The picture for the sample test. <image> Submitted Solution: ``` # -*- coding: utf-8 -*- """ Created on Fri Feb 15 17:39:24 2019 @author: avina """ n = int(input()) l = [] for _ in range(n): k,m = map(int, input().strip().split()) l.append((k,m)) l.sort(key=lambda x:x[0]) ma = 0 for i in range(n): cou = 0 for j in range(n): if abs(l[i][0] - l[j][0]) >= l[i][1] + l[i][1]: cou+=1 ma = max(cou, ma) print(ma) ```
instruction
0
95,685
13
191,370
No
output
1
95,685
13
191,371
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The clique problem is one of the most well-known NP-complete problems. Under some simplification it can be formulated as follows. Consider an undirected graph G. It is required to find a subset of vertices C of the maximum size such that any two of them are connected by an edge in graph G. Sounds simple, doesn't it? Nobody yet knows an algorithm that finds a solution to this problem in polynomial time of the size of the graph. However, as with many other NP-complete problems, the clique problem is easier if you consider a specific type of a graph. Consider n distinct points on a line. Let the i-th point have the coordinate xi and weight wi. Let's form graph G, whose vertices are these points and edges connect exactly the pairs of points (i, j), such that the distance between them is not less than the sum of their weights, or more formally: |xi - xj| β‰₯ wi + wj. Find the size of the maximum clique in such graph. Input The first line contains the integer n (1 ≀ n ≀ 200 000) β€” the number of points. Each of the next n lines contains two numbers xi, wi (0 ≀ xi ≀ 109, 1 ≀ wi ≀ 109) β€” the coordinate and the weight of a point. All xi are different. Output Print a single number β€” the number of vertexes in the maximum clique of the given graph. Examples Input 4 2 3 3 1 6 1 0 2 Output 3 Note If you happen to know how to solve this problem without using the specific properties of the graph formulated in the problem statement, then you are able to get a prize of one million dollars! The picture for the sample test. <image> Submitted Solution: ``` length = int(input()) root = [] vertices = [] for i in range(length): a, b = map(int, input().split(" ")) s, e = a - b, a + b root.append([s, 0]) root.append([e, 1]) root.sort() ini_area = length answer = 0 temp_v = 0 for i, v in enumerate(root): if v[1] == 0: temp_v += 1 answer = max(answer, min(temp_v + 1, ini_area + 1)) elif v[1] == 1: ini_area -= 1 print(answer) ```
instruction
0
95,686
13
191,372
No
output
1
95,686
13
191,373
Provide tags and a correct Python 3 solution for this coding contest problem. Each New Year Timofey and his friends cut down a tree of n vertices and bring it home. After that they paint all the n its vertices, so that the i-th vertex gets color ci. Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes some vertex in hands, while all the other vertices move down so that the tree becomes rooted at the chosen vertex. After that Timofey brings the tree to a trash can. Timofey doesn't like it when many colors are mixing together. A subtree annoys him if there are vertices of different color in it. Timofey wants to find a vertex which he should take in hands so that there are no subtrees that annoy him. He doesn't consider the whole tree as a subtree since he can't see the color of the root vertex. A subtree of some vertex is a subgraph containing that vertex and all its descendants. Your task is to determine if there is a vertex, taking which in hands Timofey wouldn't be annoyed. Input The first line contains single integer n (2 ≀ n ≀ 105) β€” the number of vertices in the tree. Each of the next n - 1 lines contains two integers u and v (1 ≀ u, v ≀ n, u β‰  v), denoting there is an edge between vertices u and v. It is guaranteed that the given graph is a tree. The next line contains n integers c1, c2, ..., cn (1 ≀ ci ≀ 105), denoting the colors of the vertices. Output Print "NO" in a single line, if Timofey can't take the tree in such a way that it doesn't annoy him. Otherwise print "YES" in the first line. In the second line print the index of the vertex which Timofey should take in hands. If there are multiple answers, print any of them. Examples Input 4 1 2 2 3 3 4 1 2 1 1 Output YES 2 Input 3 1 2 2 3 1 2 3 Output YES 2 Input 4 1 2 2 3 3 4 1 2 1 2 Output NO
instruction
0
95,747
13
191,494
Tags: dfs and similar, dp, dsu, graphs, implementation, trees Correct Solution: ``` def main(): n = int(input()) edges = [] for _ in range(n - 1): u, v = map(int, input().split()) u -= 1 v -= 1 edges.append((u, v)) colors = list(map(int, input().split())) suspect = [(u, v) for (u, v) in edges if colors[u] != colors[v]] if len(suspect) == 0: print("YES") print(1) else: cands = set(suspect[0]) for u, v in suspect: cands &= set([u, v]) if len(cands) == 0: print("NO") else: print("YES") e = list(cands)[0] print(e + 1) main() ```
output
1
95,747
13
191,495
Provide tags and a correct Python 3 solution for this coding contest problem. Each New Year Timofey and his friends cut down a tree of n vertices and bring it home. After that they paint all the n its vertices, so that the i-th vertex gets color ci. Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes some vertex in hands, while all the other vertices move down so that the tree becomes rooted at the chosen vertex. After that Timofey brings the tree to a trash can. Timofey doesn't like it when many colors are mixing together. A subtree annoys him if there are vertices of different color in it. Timofey wants to find a vertex which he should take in hands so that there are no subtrees that annoy him. He doesn't consider the whole tree as a subtree since he can't see the color of the root vertex. A subtree of some vertex is a subgraph containing that vertex and all its descendants. Your task is to determine if there is a vertex, taking which in hands Timofey wouldn't be annoyed. Input The first line contains single integer n (2 ≀ n ≀ 105) β€” the number of vertices in the tree. Each of the next n - 1 lines contains two integers u and v (1 ≀ u, v ≀ n, u β‰  v), denoting there is an edge between vertices u and v. It is guaranteed that the given graph is a tree. The next line contains n integers c1, c2, ..., cn (1 ≀ ci ≀ 105), denoting the colors of the vertices. Output Print "NO" in a single line, if Timofey can't take the tree in such a way that it doesn't annoy him. Otherwise print "YES" in the first line. In the second line print the index of the vertex which Timofey should take in hands. If there are multiple answers, print any of them. Examples Input 4 1 2 2 3 3 4 1 2 1 1 Output YES 2 Input 3 1 2 2 3 1 2 3 Output YES 2 Input 4 1 2 2 3 3 4 1 2 1 2 Output NO
instruction
0
95,748
13
191,496
Tags: dfs and similar, dp, dsu, graphs, implementation, trees Correct Solution: ``` import sys, os, io def rs(): return sys.stdin.readline().rstrip() def ri(): return int(sys.stdin.readline()) def ria(): return list(map(int, sys.stdin.readline().split())) def ws(s): sys.stdout.write(s + '\n') def wi(n): sys.stdout.write(str(n) + '\n') def wia(a): sys.stdout.write(' '.join([str(x) for x in a]) + '\n') import math,datetime,functools,itertools,operator,bisect,fractions,statistics from collections import deque,defaultdict,OrderedDict,Counter from fractions import Fraction from decimal import Decimal from sys import stdout from heapq import heappush, heappop, heapify ,_heapify_max,_heappop_max,nsmallest,nlargest # sys.setrecursionlimit(111111) INF=999999999999999999999999 alphabets="abcdefghijklmnopqrstuvwxyz" class SortedList: def __init__(self, iterable=[], _load=200): """Initialize sorted list instance.""" values = sorted(iterable) self._len = _len = len(values) self._load = _load self._lists = _lists = [values[i:i + _load] for i in range(0, _len, _load)] self._list_lens = [len(_list) for _list in _lists] self._mins = [_list[0] for _list in _lists] self._fen_tree = [] self._rebuild = True def _fen_build(self): """Build a fenwick tree instance.""" self._fen_tree[:] = self._list_lens _fen_tree = self._fen_tree for i in range(len(_fen_tree)): if i | i + 1 < len(_fen_tree): _fen_tree[i | i + 1] += _fen_tree[i] self._rebuild = False def _fen_update(self, index, value): """Update `fen_tree[index] += value`.""" if not self._rebuild: _fen_tree = self._fen_tree while index < len(_fen_tree): _fen_tree[index] += value index |= index + 1 def _fen_query(self, end): """Return `sum(_fen_tree[:end])`.""" if self._rebuild: self._fen_build() _fen_tree = self._fen_tree x = 0 while end: x += _fen_tree[end - 1] end &= end - 1 return x def _fen_findkth(self, k): """Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`).""" _list_lens = self._list_lens if k < _list_lens[0]: return 0, k if k >= self._len - _list_lens[-1]: return len(_list_lens) - 1, k + _list_lens[-1] - self._len if self._rebuild: self._fen_build() _fen_tree = self._fen_tree idx = -1 for d in reversed(range(len(_fen_tree).bit_length())): right_idx = idx + (1 << d) if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]: idx = right_idx k -= _fen_tree[idx] return idx + 1, k def _delete(self, pos, idx): """Delete value at the given `(pos, idx)`.""" _lists = self._lists _mins = self._mins _list_lens = self._list_lens self._len -= 1 self._fen_update(pos, -1) del _lists[pos][idx] _list_lens[pos] -= 1 if _list_lens[pos]: _mins[pos] = _lists[pos][0] else: del _lists[pos] del _list_lens[pos] del _mins[pos] self._rebuild = True def _loc_left(self, value): """Return an index pair that corresponds to the first position of `value` in the sorted list.""" if not self._len: return 0, 0 _lists = self._lists _mins = self._mins lo, pos = -1, len(_lists) - 1 while lo + 1 < pos: mi = (lo + pos) >> 1 if value <= _mins[mi]: pos = mi else: lo = mi if pos and value <= _lists[pos - 1][-1]: pos -= 1 _list = _lists[pos] lo, idx = -1, len(_list) while lo + 1 < idx: mi = (lo + idx) >> 1 if value <= _list[mi]: idx = mi else: lo = mi return pos, idx def _loc_right(self, value): """Return an index pair that corresponds to the last position of `value` in the sorted list.""" if not self._len: return 0, 0 _lists = self._lists _mins = self._mins pos, hi = 0, len(_lists) while pos + 1 < hi: mi = (pos + hi) >> 1 if value < _mins[mi]: hi = mi else: pos = mi _list = _lists[pos] lo, idx = -1, len(_list) while lo + 1 < idx: mi = (lo + idx) >> 1 if value < _list[mi]: idx = mi else: lo = mi return pos, idx def add(self, value): """Add `value` to sorted list.""" _load = self._load _lists = self._lists _mins = self._mins _list_lens = self._list_lens self._len += 1 if _lists: pos, idx = self._loc_right(value) self._fen_update(pos, 1) _list = _lists[pos] _list.insert(idx, value) _list_lens[pos] += 1 _mins[pos] = _list[0] if _load + _load < len(_list): _lists.insert(pos + 1, _list[_load:]) _list_lens.insert(pos + 1, len(_list) - _load) _mins.insert(pos + 1, _list[_load]) _list_lens[pos] = _load del _list[_load:] self._rebuild = True else: _lists.append([value]) _mins.append(value) _list_lens.append(1) self._rebuild = True def discard(self, value): """Remove `value` from sorted list if it is a member.""" _lists = self._lists if _lists: pos, idx = self._loc_right(value) if idx and _lists[pos][idx - 1] == value: self._delete(pos, idx - 1) def remove(self, value): """Remove `value` from sorted list; `value` must be a member.""" _len = self._len self.discard(value) if _len == self._len: raise ValueError('{0!r} not in list'.format(value)) def pop(self, index=-1): """Remove and return value at `index` in sorted list.""" pos, idx = self._fen_findkth(self._len + index if index < 0 else index) value = self._lists[pos][idx] self._delete(pos, idx) return value def bisect_left(self, value): """Return the first index to insert `value` in the sorted list.""" pos, idx = self._loc_left(value) return self._fen_query(pos) + idx def bisect_right(self, value): """Return the last index to insert `value` in the sorted list.""" pos, idx = self._loc_right(value) return self._fen_query(pos) + idx def count(self, value): """Return number of occurrences of `value` in the sorted list.""" return self.bisect_right(value) - self.bisect_left(value) def __len__(self): """Return the size of the sorted list.""" return self._len def __getitem__(self, index): """Lookup value at `index` in sorted list.""" pos, idx = self._fen_findkth(self._len + index if index < 0 else index) return self._lists[pos][idx] def __delitem__(self, index): """Remove value at `index` from sorted list.""" pos, idx = self._fen_findkth(self._len + index if index < 0 else index) self._delete(pos, idx) def __contains__(self, value): """Return true if `value` is an element of the sorted list.""" _lists = self._lists if _lists: pos, idx = self._loc_left(value) return idx < len(_lists[pos]) and _lists[pos][idx] == value return False def __iter__(self): """Return an iterator over the sorted list.""" return (value for _list in self._lists for value in _list) def __reversed__(self): """Return a reverse iterator over the sorted list.""" return (value for _list in reversed(self._lists) for value in reversed(_list)) def __repr__(self): """Return string representation of sorted list.""" return 'SortedList({0})'.format(list(self)) class SegTree: def __init__(self, n): self.N = 1 << n.bit_length() self.tree = [0] * (self.N<<1) def update(self, i, j, v): i += self.N j += self.N while i <= j: if i%2==1: self.tree[i] += v if j%2==0: self.tree[j] += v i, j = (i+1) >> 1, (j-1) >> 1 def query(self, i): v = 0 i += self.N while i > 0: v += self.tree[i] i >>= 1 return v def SieveOfEratosthenes(limit): """Returns all primes not greater than limit.""" isPrime = [True]*(limit+1) isPrime[0] = isPrime[1] = False primes = [] for i in range(2, limit+1): if not isPrime[i]:continue primes += [i] for j in range(i*i, limit+1, i): isPrime[j] = False return primes def main(): mod=1000000007 # InverseofNumber(mod) # InverseofFactorial(mod) # factorial(mod) starttime=datetime.datetime.now() if(os.path.exists('input.txt')): sys.stdin = open("input.txt","r") sys.stdout = open("output.txt","w") ###CODE tc = 1 for _ in range(tc): n=ri() graph=[[] for i in range(n+1)] cntdiffcolorededges=0 edges=[] diffcoledges={} for i in range(n-1): a,b=ria() edges.append([a,b]) graph[a].append(b) graph[b].append(a) col=[0]+ria() for a,b in edges: if col[a]!=col[b]: cntdiffcolorededges+=2 diffcoledges[a]=diffcoledges.get(a,0)+1 diffcoledges[b]=diffcoledges.get(b,0)+1 if cntdiffcolorededges==0: ws("YES") wi(1) exit() for i in diffcoledges: if 2*diffcoledges[i]==cntdiffcolorededges: ws("YES") wi(i) exit() ws("NO") #<--Solving Area Ends endtime=datetime.datetime.now() time=(endtime-starttime).total_seconds()*1000 if(os.path.exists('input.txt')): print("Time:",time,"ms") class FastReader(io.IOBase): newlines = 0 def __init__(self, fd, chunk_size=1024 * 8): self._fd = fd self._chunk_size = chunk_size self.buffer = io.BytesIO() def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self, size=-1): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size if size == -1 else size)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() class FastWriter(io.IOBase): def __init__(self, fd): self._fd = fd self.buffer = io.BytesIO() self.write = self.buffer.write def flush(self): os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class FastStdin(io.IOBase): def __init__(self, fd=0): self.buffer = FastReader(fd) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") class FastStdout(io.IOBase): def __init__(self, fd=1): self.buffer = FastWriter(fd) self.write = lambda s: self.buffer.write(s.encode("ascii")) self.flush = self.buffer.flush if __name__ == '__main__': sys.stdin = FastStdin() sys.stdout = FastStdout() main() ```
output
1
95,748
13
191,497
Provide tags and a correct Python 3 solution for this coding contest problem. Each New Year Timofey and his friends cut down a tree of n vertices and bring it home. After that they paint all the n its vertices, so that the i-th vertex gets color ci. Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes some vertex in hands, while all the other vertices move down so that the tree becomes rooted at the chosen vertex. After that Timofey brings the tree to a trash can. Timofey doesn't like it when many colors are mixing together. A subtree annoys him if there are vertices of different color in it. Timofey wants to find a vertex which he should take in hands so that there are no subtrees that annoy him. He doesn't consider the whole tree as a subtree since he can't see the color of the root vertex. A subtree of some vertex is a subgraph containing that vertex and all its descendants. Your task is to determine if there is a vertex, taking which in hands Timofey wouldn't be annoyed. Input The first line contains single integer n (2 ≀ n ≀ 105) β€” the number of vertices in the tree. Each of the next n - 1 lines contains two integers u and v (1 ≀ u, v ≀ n, u β‰  v), denoting there is an edge between vertices u and v. It is guaranteed that the given graph is a tree. The next line contains n integers c1, c2, ..., cn (1 ≀ ci ≀ 105), denoting the colors of the vertices. Output Print "NO" in a single line, if Timofey can't take the tree in such a way that it doesn't annoy him. Otherwise print "YES" in the first line. In the second line print the index of the vertex which Timofey should take in hands. If there are multiple answers, print any of them. Examples Input 4 1 2 2 3 3 4 1 2 1 1 Output YES 2 Input 3 1 2 2 3 1 2 3 Output YES 2 Input 4 1 2 2 3 3 4 1 2 1 2 Output NO
instruction
0
95,749
13
191,498
Tags: dfs and similar, dp, dsu, graphs, implementation, trees Correct Solution: ``` # import itertools # import bisect import math from collections import defaultdict import os import sys from io import BytesIO, IOBase # sys.setrecursionlimit(10 ** 5) ii = lambda: int(input()) lmii = lambda: list(map(int, input().split())) slmii = lambda: sorted(map(int, input().split())) li = lambda: list(input()) mii = lambda: map(int, input().split()) msi = lambda: map(str, input().split()) def gcd(a, b): if b == 0: return a return gcd(b, a % b) def lcm(a, b): return (a * b) // gcd(a, b) def main(): # for _ in " " * int(input()): n = ii() adj = defaultdict(list) for i in range(n - 1): x, y = mii() adj[x].append(y) adj[y].append(x) col = lmii() ans = [] if len(set(col)) == 1: print("YES") print(1) else: for i in adj: for j in adj[i]: if col[i - 1] != col[j - 1]: ans.append([i, j]) if len(ans) == 2: print("YES") print(ans[0][0]) else: s = {ans[0][1], ans[0][0]} for i in ans: s.intersection_update({i[0], i[1]}) if len(s) == 1: print("YES") print(s.pop()) else: print("NO") 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") if __name__ == "__main__": main() ```
output
1
95,749
13
191,499
Provide tags and a correct Python 3 solution for this coding contest problem. Each New Year Timofey and his friends cut down a tree of n vertices and bring it home. After that they paint all the n its vertices, so that the i-th vertex gets color ci. Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes some vertex in hands, while all the other vertices move down so that the tree becomes rooted at the chosen vertex. After that Timofey brings the tree to a trash can. Timofey doesn't like it when many colors are mixing together. A subtree annoys him if there are vertices of different color in it. Timofey wants to find a vertex which he should take in hands so that there are no subtrees that annoy him. He doesn't consider the whole tree as a subtree since he can't see the color of the root vertex. A subtree of some vertex is a subgraph containing that vertex and all its descendants. Your task is to determine if there is a vertex, taking which in hands Timofey wouldn't be annoyed. Input The first line contains single integer n (2 ≀ n ≀ 105) β€” the number of vertices in the tree. Each of the next n - 1 lines contains two integers u and v (1 ≀ u, v ≀ n, u β‰  v), denoting there is an edge between vertices u and v. It is guaranteed that the given graph is a tree. The next line contains n integers c1, c2, ..., cn (1 ≀ ci ≀ 105), denoting the colors of the vertices. Output Print "NO" in a single line, if Timofey can't take the tree in such a way that it doesn't annoy him. Otherwise print "YES" in the first line. In the second line print the index of the vertex which Timofey should take in hands. If there are multiple answers, print any of them. Examples Input 4 1 2 2 3 3 4 1 2 1 1 Output YES 2 Input 3 1 2 2 3 1 2 3 Output YES 2 Input 4 1 2 2 3 3 4 1 2 1 2 Output NO
instruction
0
95,750
13
191,500
Tags: dfs and similar, dp, dsu, graphs, implementation, trees Correct Solution: ``` n = int(input()) arr = [] brr = [] for i in range(n-1): u,v = list(map(int,input().split())) arr.append(u) brr.append(v) color = list(map(int,input().split())) ans = [] for i in range(n-1): if color[arr[i]-1]!=color[brr[i]-1]: if ans==[]: ans+=[arr[i],brr[i]] else: if arr[i] in ans and brr[i] in ans: print("NO") exit() elif arr[i] in ans: ans = [arr[i]] elif brr[i] in ans: ans = [brr[i]] else: print("NO") exit() print("YES") if len(ans)==0: ans.append(1) print(ans[0]) ```
output
1
95,750
13
191,501
Provide tags and a correct Python 3 solution for this coding contest problem. Each New Year Timofey and his friends cut down a tree of n vertices and bring it home. After that they paint all the n its vertices, so that the i-th vertex gets color ci. Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes some vertex in hands, while all the other vertices move down so that the tree becomes rooted at the chosen vertex. After that Timofey brings the tree to a trash can. Timofey doesn't like it when many colors are mixing together. A subtree annoys him if there are vertices of different color in it. Timofey wants to find a vertex which he should take in hands so that there are no subtrees that annoy him. He doesn't consider the whole tree as a subtree since he can't see the color of the root vertex. A subtree of some vertex is a subgraph containing that vertex and all its descendants. Your task is to determine if there is a vertex, taking which in hands Timofey wouldn't be annoyed. Input The first line contains single integer n (2 ≀ n ≀ 105) β€” the number of vertices in the tree. Each of the next n - 1 lines contains two integers u and v (1 ≀ u, v ≀ n, u β‰  v), denoting there is an edge between vertices u and v. It is guaranteed that the given graph is a tree. The next line contains n integers c1, c2, ..., cn (1 ≀ ci ≀ 105), denoting the colors of the vertices. Output Print "NO" in a single line, if Timofey can't take the tree in such a way that it doesn't annoy him. Otherwise print "YES" in the first line. In the second line print the index of the vertex which Timofey should take in hands. If there are multiple answers, print any of them. Examples Input 4 1 2 2 3 3 4 1 2 1 1 Output YES 2 Input 3 1 2 2 3 1 2 3 Output YES 2 Input 4 1 2 2 3 3 4 1 2 1 2 Output NO
instruction
0
95,751
13
191,502
Tags: dfs and similar, dp, dsu, graphs, implementation, trees Correct Solution: ``` import sys def answer(n, u, v, colors): suspect = [] for i in range(n-1): if colors[u[i]-1] != colors[v[i]-1]: suspect.append([u[i], v[i]]) if len(suspect) == 0: print('YES') print('1') return s = set(suspect[0]) for tup in suspect: s &= set(tup) if len(s) == 0: print('NO') return else: print('YES') print(s.pop()) return #null. Print 1 or 2 lines. def main(): n = int(sys.stdin.readline()) u = [0 for _ in range(n)] v = [0 for _ in range(n)] for i in range(n-1): u[i], v[i] = map(int, sys.stdin.readline().split()) colors = list(map(int, sys.stdin.readline().split())) answer(n, u, v, colors) return main() ```
output
1
95,751
13
191,503
Provide tags and a correct Python 3 solution for this coding contest problem. Each New Year Timofey and his friends cut down a tree of n vertices and bring it home. After that they paint all the n its vertices, so that the i-th vertex gets color ci. Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes some vertex in hands, while all the other vertices move down so that the tree becomes rooted at the chosen vertex. After that Timofey brings the tree to a trash can. Timofey doesn't like it when many colors are mixing together. A subtree annoys him if there are vertices of different color in it. Timofey wants to find a vertex which he should take in hands so that there are no subtrees that annoy him. He doesn't consider the whole tree as a subtree since he can't see the color of the root vertex. A subtree of some vertex is a subgraph containing that vertex and all its descendants. Your task is to determine if there is a vertex, taking which in hands Timofey wouldn't be annoyed. Input The first line contains single integer n (2 ≀ n ≀ 105) β€” the number of vertices in the tree. Each of the next n - 1 lines contains two integers u and v (1 ≀ u, v ≀ n, u β‰  v), denoting there is an edge between vertices u and v. It is guaranteed that the given graph is a tree. The next line contains n integers c1, c2, ..., cn (1 ≀ ci ≀ 105), denoting the colors of the vertices. Output Print "NO" in a single line, if Timofey can't take the tree in such a way that it doesn't annoy him. Otherwise print "YES" in the first line. In the second line print the index of the vertex which Timofey should take in hands. If there are multiple answers, print any of them. Examples Input 4 1 2 2 3 3 4 1 2 1 1 Output YES 2 Input 3 1 2 2 3 1 2 3 Output YES 2 Input 4 1 2 2 3 3 4 1 2 1 2 Output NO
instruction
0
95,752
13
191,504
Tags: dfs and similar, dp, dsu, graphs, implementation, trees Correct Solution: ``` n = int(input()) edges = [] for _ in range(n-1): u,v = map(int,input().split()) edges.append([u,v]) ct = [0]+list(map(int,input().split())) ds = [-1]+[0]*n vs = 0 for u,v in edges: if ct[u]!=ct[v]: ds[u]+=1 ds[v]+=1 vs+=1 if vs == max(ds): print("YES") print(ds.index(vs)) else: print("NO") ```
output
1
95,752
13
191,505
Provide tags and a correct Python 3 solution for this coding contest problem. Each New Year Timofey and his friends cut down a tree of n vertices and bring it home. After that they paint all the n its vertices, so that the i-th vertex gets color ci. Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes some vertex in hands, while all the other vertices move down so that the tree becomes rooted at the chosen vertex. After that Timofey brings the tree to a trash can. Timofey doesn't like it when many colors are mixing together. A subtree annoys him if there are vertices of different color in it. Timofey wants to find a vertex which he should take in hands so that there are no subtrees that annoy him. He doesn't consider the whole tree as a subtree since he can't see the color of the root vertex. A subtree of some vertex is a subgraph containing that vertex and all its descendants. Your task is to determine if there is a vertex, taking which in hands Timofey wouldn't be annoyed. Input The first line contains single integer n (2 ≀ n ≀ 105) β€” the number of vertices in the tree. Each of the next n - 1 lines contains two integers u and v (1 ≀ u, v ≀ n, u β‰  v), denoting there is an edge between vertices u and v. It is guaranteed that the given graph is a tree. The next line contains n integers c1, c2, ..., cn (1 ≀ ci ≀ 105), denoting the colors of the vertices. Output Print "NO" in a single line, if Timofey can't take the tree in such a way that it doesn't annoy him. Otherwise print "YES" in the first line. In the second line print the index of the vertex which Timofey should take in hands. If there are multiple answers, print any of them. Examples Input 4 1 2 2 3 3 4 1 2 1 1 Output YES 2 Input 3 1 2 2 3 1 2 3 Output YES 2 Input 4 1 2 2 3 3 4 1 2 1 2 Output NO
instruction
0
95,753
13
191,506
Tags: dfs and similar, dp, dsu, graphs, implementation, trees Correct Solution: ``` import sys import collections import itertools n = int(sys.stdin.readline()) graph = collections.defaultdict(list) for _ in range(n - 1): u, v = map(int, str.split(sys.stdin.readline())) graph[u].append(v) graph[v].append(u) colors = tuple(map(int, str.split(sys.stdin.readline()))) root = None root_possible = [] for node in graph: diff_subs = [] for sub_node in graph[node]: if colors[node - 1] != colors[sub_node - 1]: diff_subs.append(sub_node) if len(diff_subs) > 1: if root is None: root = node else: print("NO") exit() elif len(diff_subs) == 1: root_possible.append((node, diff_subs[0])) root_possible_set = set(itertools.chain.from_iterable(root_possible)) if root: print("YES") print(root) elif not root_possible: print("YES") print(1) elif len(root_possible_set) == 2: print("YES") print(next(iter(root_possible_set))) else: print("NO") ```
output
1
95,753
13
191,507
Provide tags and a correct Python 3 solution for this coding contest problem. Each New Year Timofey and his friends cut down a tree of n vertices and bring it home. After that they paint all the n its vertices, so that the i-th vertex gets color ci. Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes some vertex in hands, while all the other vertices move down so that the tree becomes rooted at the chosen vertex. After that Timofey brings the tree to a trash can. Timofey doesn't like it when many colors are mixing together. A subtree annoys him if there are vertices of different color in it. Timofey wants to find a vertex which he should take in hands so that there are no subtrees that annoy him. He doesn't consider the whole tree as a subtree since he can't see the color of the root vertex. A subtree of some vertex is a subgraph containing that vertex and all its descendants. Your task is to determine if there is a vertex, taking which in hands Timofey wouldn't be annoyed. Input The first line contains single integer n (2 ≀ n ≀ 105) β€” the number of vertices in the tree. Each of the next n - 1 lines contains two integers u and v (1 ≀ u, v ≀ n, u β‰  v), denoting there is an edge between vertices u and v. It is guaranteed that the given graph is a tree. The next line contains n integers c1, c2, ..., cn (1 ≀ ci ≀ 105), denoting the colors of the vertices. Output Print "NO" in a single line, if Timofey can't take the tree in such a way that it doesn't annoy him. Otherwise print "YES" in the first line. In the second line print the index of the vertex which Timofey should take in hands. If there are multiple answers, print any of them. Examples Input 4 1 2 2 3 3 4 1 2 1 1 Output YES 2 Input 3 1 2 2 3 1 2 3 Output YES 2 Input 4 1 2 2 3 3 4 1 2 1 2 Output NO
instruction
0
95,754
13
191,508
Tags: dfs and similar, dp, dsu, graphs, implementation, trees Correct Solution: ``` n=int(input()) ip=[[] for i in range(n)] for i in range(n-1): a,b=map(int,input().split()) a-=1 b-=1 ip[a].append(b) ip[b].append(a) col=list(map(int,input().split())) cs=[0 for i in range(n)] for i in range(n): count=0 for j in ip[i]: if col[j]!=col[i]: count+=1 cs[i]=count #print(cs) #print(ip) count=0 c1=0 for i in range(n): if cs[i]==0: continue elif cs[i]==1: c1+=1 ans1=i+1 else: #print("csi",cs[i]) count+=1 ans=i+1 #print(count) if count==0: if c1==0: print('YES') print(1) elif c1==2: print('YES') print(ans1) else: print('NO') elif count==1: if c1<=len(ip[ans-1]): print('YES') print(ans) else: print('NO') else: print('NO') ```
output
1
95,754
13
191,509
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Each New Year Timofey and his friends cut down a tree of n vertices and bring it home. After that they paint all the n its vertices, so that the i-th vertex gets color ci. Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes some vertex in hands, while all the other vertices move down so that the tree becomes rooted at the chosen vertex. After that Timofey brings the tree to a trash can. Timofey doesn't like it when many colors are mixing together. A subtree annoys him if there are vertices of different color in it. Timofey wants to find a vertex which he should take in hands so that there are no subtrees that annoy him. He doesn't consider the whole tree as a subtree since he can't see the color of the root vertex. A subtree of some vertex is a subgraph containing that vertex and all its descendants. Your task is to determine if there is a vertex, taking which in hands Timofey wouldn't be annoyed. Input The first line contains single integer n (2 ≀ n ≀ 105) β€” the number of vertices in the tree. Each of the next n - 1 lines contains two integers u and v (1 ≀ u, v ≀ n, u β‰  v), denoting there is an edge between vertices u and v. It is guaranteed that the given graph is a tree. The next line contains n integers c1, c2, ..., cn (1 ≀ ci ≀ 105), denoting the colors of the vertices. Output Print "NO" in a single line, if Timofey can't take the tree in such a way that it doesn't annoy him. Otherwise print "YES" in the first line. In the second line print the index of the vertex which Timofey should take in hands. If there are multiple answers, print any of them. Examples Input 4 1 2 2 3 3 4 1 2 1 1 Output YES 2 Input 3 1 2 2 3 1 2 3 Output YES 2 Input 4 1 2 2 3 3 4 1 2 1 2 Output NO Submitted Solution: ``` n=int(input()) graph=dict() for i in range(1,n+1): graph[i]=[] diff=[] for i in range(n-1): u,v=map(int,input().split()) graph[u].append(v) graph[v].append(u) color=list(map(int,input().split())) # print(color) # print(graph) flag=0 # used to indicate if two different colors nodes are present in an edge for i in range(1,n+1): if(graph[i]!=[]): for j in graph[i]: if(color[i-1]!=color[j-1]): diff.append(i) diff.append(j) flag=1 break if(flag==1): break # print(diff) #check=[-1 for i in range(n)] def dfs(graph,node,col,parentnode): # print(node,col,color[node-1]) # global check if(color[node-1]!=col): return -1 # check[node-1]=0 if(graph[node]!=[]): for i in graph[node]: if(i!=parentnode): f1=dfs(graph,i,col,node) if(f1==-1): return -1 return 1 if(flag==0): # single color nodes are present in the entire tree print("YES") print(n) else: # different color present # print("check",check) #check[diff[0]-1]=0 f=1 for i in graph[diff[0]]: f=dfs(graph,i,color[i-1],diff[0]) # print(f,i) if(f==-1): # some of the children nodes are of different color break if(f!=-1):# if all the children satisfy the condition # flag1=0 # for i in range(n): # if(check[i]==-1): # for j in range(i+1,n): # if(check[j]==-1 and color[j]!=color[i]): # flag1=-1 # two different colors found # break # if(flag1==-1): # break # if(flag1==0): print("YES") print(diff[0]) # else: # f=-1 if(f==-1): # the checking of the children node has started # for i in range(n): # check[i]=-1 # check[diff[1]-1]=0 # print("check1",check1) f2=1 for i in graph[diff[1]]: f2=dfs(graph,i,color[i-1],diff[1]) # print(f2,i) if(f2==-1): break # print(f2,check1) if(f2==-1): print("NO") else:# if all the children satisfy the condition # print(color) # flag1=0 # for i in range(n): # if(check[i]==-1): # for j in range(i+1,n): # if(check[j]==-1 and color[j]!=color[i]): # flag1=-1 # two different colors found # break # if(flag1==-1): # break # if(flag1==0): print("YES") print(diff[1]) # else: # print("NO") ```
instruction
0
95,755
13
191,510
Yes
output
1
95,755
13
191,511
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Each New Year Timofey and his friends cut down a tree of n vertices and bring it home. After that they paint all the n its vertices, so that the i-th vertex gets color ci. Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes some vertex in hands, while all the other vertices move down so that the tree becomes rooted at the chosen vertex. After that Timofey brings the tree to a trash can. Timofey doesn't like it when many colors are mixing together. A subtree annoys him if there are vertices of different color in it. Timofey wants to find a vertex which he should take in hands so that there are no subtrees that annoy him. He doesn't consider the whole tree as a subtree since he can't see the color of the root vertex. A subtree of some vertex is a subgraph containing that vertex and all its descendants. Your task is to determine if there is a vertex, taking which in hands Timofey wouldn't be annoyed. Input The first line contains single integer n (2 ≀ n ≀ 105) β€” the number of vertices in the tree. Each of the next n - 1 lines contains two integers u and v (1 ≀ u, v ≀ n, u β‰  v), denoting there is an edge between vertices u and v. It is guaranteed that the given graph is a tree. The next line contains n integers c1, c2, ..., cn (1 ≀ ci ≀ 105), denoting the colors of the vertices. Output Print "NO" in a single line, if Timofey can't take the tree in such a way that it doesn't annoy him. Otherwise print "YES" in the first line. In the second line print the index of the vertex which Timofey should take in hands. If there are multiple answers, print any of them. Examples Input 4 1 2 2 3 3 4 1 2 1 1 Output YES 2 Input 3 1 2 2 3 1 2 3 Output YES 2 Input 4 1 2 2 3 3 4 1 2 1 2 Output NO Submitted Solution: ``` # Author : nitish420 -------------------------------------------------------------------- import os import sys from io import BytesIO, IOBase def main(): n=int(input()) tree=[[] for _ in range(n+1)] for _ in range(n-1): a,b=map(int,input().split()) tree[a].append(b) tree[b].append(a) arr=[0]+list(map(int,input().split())) root1,root2=0,0 for i in range(1,n+1): for item in tree[i]: if arr[i]!=arr[item]: root1=i root2=item break if root2: break if not root2: print("YES") print(1) exit() # print(root2,root1) # first taking root1 an ans ans=1 vis=[0]*(n+1) idx=[0]*(n+1) vis[root1]=1 for item in tree[root1]: stack=[item] while stack: x=stack[-1] vis[x]=1 y=idx[x] if y==len(tree[x]): stack.pop() else: z=tree[x][y] if vis[z]==0: if arr[x]!=arr[z]: ans=0 break stack.append(z) idx[x]+=1 if ans==0: break if ans==1: print("YES") print(root1) exit() ans=1 # now taking root two vis=[0]*(n+1) idx=[0]*(n+1) vis[root2]=1 for item in tree[root2]: stack=[item] while stack: x=stack[-1] vis[x]=1 y=idx[x] if y==len(tree[x]): stack.pop() else: z=tree[x][y] if vis[z]==0: if arr[x]!=arr[z]: ans=0 break stack.append(z) idx[x]+=1 if ans==0: break if ans: print("YES") print(root2) else: print("NO") # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = 'x' in file.mode or 'r' not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b'\n') + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode('ascii')) self.read = lambda: self.buffer.read().decode('ascii') self.readline = lambda: self.buffer.readline().decode('ascii') sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip('\r\n') # endregion if __name__ == '__main__': main() ```
instruction
0
95,756
13
191,512
Yes
output
1
95,756
13
191,513
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Each New Year Timofey and his friends cut down a tree of n vertices and bring it home. After that they paint all the n its vertices, so that the i-th vertex gets color ci. Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes some vertex in hands, while all the other vertices move down so that the tree becomes rooted at the chosen vertex. After that Timofey brings the tree to a trash can. Timofey doesn't like it when many colors are mixing together. A subtree annoys him if there are vertices of different color in it. Timofey wants to find a vertex which he should take in hands so that there are no subtrees that annoy him. He doesn't consider the whole tree as a subtree since he can't see the color of the root vertex. A subtree of some vertex is a subgraph containing that vertex and all its descendants. Your task is to determine if there is a vertex, taking which in hands Timofey wouldn't be annoyed. Input The first line contains single integer n (2 ≀ n ≀ 105) β€” the number of vertices in the tree. Each of the next n - 1 lines contains two integers u and v (1 ≀ u, v ≀ n, u β‰  v), denoting there is an edge between vertices u and v. It is guaranteed that the given graph is a tree. The next line contains n integers c1, c2, ..., cn (1 ≀ ci ≀ 105), denoting the colors of the vertices. Output Print "NO" in a single line, if Timofey can't take the tree in such a way that it doesn't annoy him. Otherwise print "YES" in the first line. In the second line print the index of the vertex which Timofey should take in hands. If there are multiple answers, print any of them. Examples Input 4 1 2 2 3 3 4 1 2 1 1 Output YES 2 Input 3 1 2 2 3 1 2 3 Output YES 2 Input 4 1 2 2 3 3 4 1 2 1 2 Output NO Submitted Solution: ``` import sys class UnionFind: def __init__(self, sz): self.__ranks = [1] * sz self.__sizes = [1] * sz self.__parents = [ i for i in range(sz) ] def find_parent(self, x): if x == self.__parents[x]: return x else: self.__parents[x] = self.find_parent( self.__parents[x] ) return self.__parents[x] def same(self, x, y): return self.find_parent(x) == self.find_parent(y) def unite(self, x, y): px = self.find_parent(x) py = self.find_parent(y) if px == py: return if self.__ranks[px] > self.__ranks[py]: self.__parents[py] = px self.__sizes[px] += self.__sizes[py] else: self.__parents[px] = py self.__sizes[py] += self.__sizes[px] if self.__ranks[px] == self.__ranks[py]: self.__ranks[py] += 1 def size(self, n): return self.__sizes[n] #### def main(): n = int(input()) edge = {} for i in range(n - 1): u,v = map(int, sys.stdin.readline().split()) if u not in edge: edge[u] = [] if v not in edge: edge[v] = [] edge[u].append(v) edge[v].append(u) colors = [-1] * (n + 1) for i,c in enumerate(map(int, sys.stdin.readline().split())): colors[i + 1] = c uf = UnionFind(n + 1) for u in edge.keys(): for v in edge[u]: if colors[u] == colors[v]: uf.unite(u,v) tree = set() for v in range(1,n+1): tree.add(uf.find_parent(v)) target_v = -1 ok = False for u in range(1,n+1): cnt = set() for v in edge[u]: cnt.add(uf.find_parent(v)) if len(cnt) == len(tree) - (1 if uf.size(uf.find_parent(u)) == 1 else 0): ok = True target_v = u break if ok: print("YES") print(target_v) else: print("NO") if __name__ == '__main__': main() ```
instruction
0
95,757
13
191,514
Yes
output
1
95,757
13
191,515
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Each New Year Timofey and his friends cut down a tree of n vertices and bring it home. After that they paint all the n its vertices, so that the i-th vertex gets color ci. Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes some vertex in hands, while all the other vertices move down so that the tree becomes rooted at the chosen vertex. After that Timofey brings the tree to a trash can. Timofey doesn't like it when many colors are mixing together. A subtree annoys him if there are vertices of different color in it. Timofey wants to find a vertex which he should take in hands so that there are no subtrees that annoy him. He doesn't consider the whole tree as a subtree since he can't see the color of the root vertex. A subtree of some vertex is a subgraph containing that vertex and all its descendants. Your task is to determine if there is a vertex, taking which in hands Timofey wouldn't be annoyed. Input The first line contains single integer n (2 ≀ n ≀ 105) β€” the number of vertices in the tree. Each of the next n - 1 lines contains two integers u and v (1 ≀ u, v ≀ n, u β‰  v), denoting there is an edge between vertices u and v. It is guaranteed that the given graph is a tree. The next line contains n integers c1, c2, ..., cn (1 ≀ ci ≀ 105), denoting the colors of the vertices. Output Print "NO" in a single line, if Timofey can't take the tree in such a way that it doesn't annoy him. Otherwise print "YES" in the first line. In the second line print the index of the vertex which Timofey should take in hands. If there are multiple answers, print any of them. Examples Input 4 1 2 2 3 3 4 1 2 1 1 Output YES 2 Input 3 1 2 2 3 1 2 3 Output YES 2 Input 4 1 2 2 3 3 4 1 2 1 2 Output NO Submitted Solution: ``` #!/usr/bin/env python3 def ri(): return map(int, input().split()) n = int(input()) e = [] for i in range(n-1): a, b = ri() a -= 1 b -= 1 e.append([a, b]) c = list(ri()) ed = [] for ee in e: if c[ee[0]] != c[ee[1]]: ed.append(ee) if len(ed) == 0: print("YES") print(1) exit() cand = ed[0] not0 = 0 not1 = 0 for ee in ed: if cand[0] != ee[0] and cand[0] != ee[1]: not0 = 1 break for ee in ed: if cand[1] != ee[0] and cand[1] != ee[1]: not1 = 1 break if not0 == 0: print("YES") print(cand[0]+1) elif not1 == 0: print("YES") print(cand[1]+1) else: print("NO") ```
instruction
0
95,758
13
191,516
Yes
output
1
95,758
13
191,517
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Each New Year Timofey and his friends cut down a tree of n vertices and bring it home. After that they paint all the n its vertices, so that the i-th vertex gets color ci. Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes some vertex in hands, while all the other vertices move down so that the tree becomes rooted at the chosen vertex. After that Timofey brings the tree to a trash can. Timofey doesn't like it when many colors are mixing together. A subtree annoys him if there are vertices of different color in it. Timofey wants to find a vertex which he should take in hands so that there are no subtrees that annoy him. He doesn't consider the whole tree as a subtree since he can't see the color of the root vertex. A subtree of some vertex is a subgraph containing that vertex and all its descendants. Your task is to determine if there is a vertex, taking which in hands Timofey wouldn't be annoyed. Input The first line contains single integer n (2 ≀ n ≀ 105) β€” the number of vertices in the tree. Each of the next n - 1 lines contains two integers u and v (1 ≀ u, v ≀ n, u β‰  v), denoting there is an edge between vertices u and v. It is guaranteed that the given graph is a tree. The next line contains n integers c1, c2, ..., cn (1 ≀ ci ≀ 105), denoting the colors of the vertices. Output Print "NO" in a single line, if Timofey can't take the tree in such a way that it doesn't annoy him. Otherwise print "YES" in the first line. In the second line print the index of the vertex which Timofey should take in hands. If there are multiple answers, print any of them. Examples Input 4 1 2 2 3 3 4 1 2 1 1 Output YES 2 Input 3 1 2 2 3 1 2 3 Output YES 2 Input 4 1 2 2 3 3 4 1 2 1 2 Output NO Submitted Solution: ``` def dfs( v, c ): visited[v] = 1 for i in E[v]: if visited[i] == 0: if c == clr[i]: dfs( i, c) else: visited[i] = 2 gc = 0 pos = 0 clr = [] N = int(input()) visited = [ 0 for i in range(N)] E = [ [] for i in range(N) ] for i in range( N - 1 ): s = input().split(' ') a = int(s[0]) - 1 b = int(s[1]) - 1 E[a].append(b) E[b].append(a) clr = input().split(' ') for i in range(N): if visited[i] == 0: dfs(i, clr[i]) if visited[i] == 2: gc += 1 pos = i if gc == 0: print(0) if gc == 1: print('YES\n{}'.format(pos + 1)) if gc > 1: print('NO') ```
instruction
0
95,759
13
191,518
No
output
1
95,759
13
191,519
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Each New Year Timofey and his friends cut down a tree of n vertices and bring it home. After that they paint all the n its vertices, so that the i-th vertex gets color ci. Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes some vertex in hands, while all the other vertices move down so that the tree becomes rooted at the chosen vertex. After that Timofey brings the tree to a trash can. Timofey doesn't like it when many colors are mixing together. A subtree annoys him if there are vertices of different color in it. Timofey wants to find a vertex which he should take in hands so that there are no subtrees that annoy him. He doesn't consider the whole tree as a subtree since he can't see the color of the root vertex. A subtree of some vertex is a subgraph containing that vertex and all its descendants. Your task is to determine if there is a vertex, taking which in hands Timofey wouldn't be annoyed. Input The first line contains single integer n (2 ≀ n ≀ 105) β€” the number of vertices in the tree. Each of the next n - 1 lines contains two integers u and v (1 ≀ u, v ≀ n, u β‰  v), denoting there is an edge between vertices u and v. It is guaranteed that the given graph is a tree. The next line contains n integers c1, c2, ..., cn (1 ≀ ci ≀ 105), denoting the colors of the vertices. Output Print "NO" in a single line, if Timofey can't take the tree in such a way that it doesn't annoy him. Otherwise print "YES" in the first line. In the second line print the index of the vertex which Timofey should take in hands. If there are multiple answers, print any of them. Examples Input 4 1 2 2 3 3 4 1 2 1 1 Output YES 2 Input 3 1 2 2 3 1 2 3 Output YES 2 Input 4 1 2 2 3 3 4 1 2 1 2 Output NO Submitted Solution: ``` n=int(input()) dct={} dctcheck={} for i in range(n-1): u,v=map(int,input().split()) if(u in dct.keys()): dct[u].append(v) dctcheck[v]=False else: dct[u]=[v] dctcheck[u]=False dctcheck[v]=False if(v in dct.keys()): dct[v].append(u) else: dct[v]=[u] carr=list(map(int,input().split())) cset=set(carr) csetl=len(cset) def func(nd,cl,dct1): if(dct1[nd]==True): return 1 else: dct1[nd]=True if(carr[nd-1]!=cl): return 0 if(nd not in dct.keys()): return 1 for v in dct[nd]: x=func(v,cl,dct1) if(x==0): return 0 return 1 mx=-1 for key in dct.keys(): if(len(dct[key])>mx): mx=len(dct[key]) lst1=[] for key in dct.keys(): if(len(dct[key])==mx): lst1.append(key) check=1 for head in lst1: dct1=dctcheck.copy() dct1[head]=True if(head not in dct.keys()): continue if(len(dct[head])+1<csetl): check=0 continue else: # print("head--> ",head) check=1 for j in dct[head]: cl=carr[j-1] y=func(j,cl,dct1) # print("y ",y,j,cl) # print(dct1) if(y==0): check=0 break if(check==1): print("YES") print(head) exit() if(check==0): print("NO") ```
instruction
0
95,760
13
191,520
No
output
1
95,760
13
191,521
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Each New Year Timofey and his friends cut down a tree of n vertices and bring it home. After that they paint all the n its vertices, so that the i-th vertex gets color ci. Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes some vertex in hands, while all the other vertices move down so that the tree becomes rooted at the chosen vertex. After that Timofey brings the tree to a trash can. Timofey doesn't like it when many colors are mixing together. A subtree annoys him if there are vertices of different color in it. Timofey wants to find a vertex which he should take in hands so that there are no subtrees that annoy him. He doesn't consider the whole tree as a subtree since he can't see the color of the root vertex. A subtree of some vertex is a subgraph containing that vertex and all its descendants. Your task is to determine if there is a vertex, taking which in hands Timofey wouldn't be annoyed. Input The first line contains single integer n (2 ≀ n ≀ 105) β€” the number of vertices in the tree. Each of the next n - 1 lines contains two integers u and v (1 ≀ u, v ≀ n, u β‰  v), denoting there is an edge between vertices u and v. It is guaranteed that the given graph is a tree. The next line contains n integers c1, c2, ..., cn (1 ≀ ci ≀ 105), denoting the colors of the vertices. Output Print "NO" in a single line, if Timofey can't take the tree in such a way that it doesn't annoy him. Otherwise print "YES" in the first line. In the second line print the index of the vertex which Timofey should take in hands. If there are multiple answers, print any of them. Examples Input 4 1 2 2 3 3 4 1 2 1 1 Output YES 2 Input 3 1 2 2 3 1 2 3 Output YES 2 Input 4 1 2 2 3 3 4 1 2 1 2 Output NO Submitted Solution: ``` n = int(input()) tree = dict() for i in range(n-1): u, v = tuple(map(int, input().split())) if u in tree: tree[u].append(v) else: tree[u] = [v] if v in tree: tree[v].append(u) else: tree[v] = [u] colors = list(map(int, input().split())) subtrees_checked = dict() def check_subtree_color(i, c, checked): if i in subtrees_checked: if len(subtrees_checked[i][0]) > 0: if c == subtrees_checked[i][0][0]: return True else: return False elif len(subtrees_checked[i][1]) > 0: if c in subtrees_checked[i][1]: return False for u in tree[i]: if not u in checked: if colors[u-1] != c: if i in subtrees_checked: subtrees_checked[i][1].append(c) else: subtrees_checked[i] = [[], [c]] return False else: checked.add(u) if not check_subtree_color(u, c, checked): if i in subtrees_checked: subtrees_checked[i][1].append(c) else: subtrees_checked[i] = [[], [c]] return False if i in subtrees_checked: subtrees_checked[i][0].append(c) else: subtrees_checked[i] = [[c], []] return True for u in tree: for v in tree[u]: if not check_subtree_color(v, colors[v-1], {u}): break else: print("YES") print(u) break else: print("NO") ```
instruction
0
95,761
13
191,522
No
output
1
95,761
13
191,523
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Each New Year Timofey and his friends cut down a tree of n vertices and bring it home. After that they paint all the n its vertices, so that the i-th vertex gets color ci. Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes some vertex in hands, while all the other vertices move down so that the tree becomes rooted at the chosen vertex. After that Timofey brings the tree to a trash can. Timofey doesn't like it when many colors are mixing together. A subtree annoys him if there are vertices of different color in it. Timofey wants to find a vertex which he should take in hands so that there are no subtrees that annoy him. He doesn't consider the whole tree as a subtree since he can't see the color of the root vertex. A subtree of some vertex is a subgraph containing that vertex and all its descendants. Your task is to determine if there is a vertex, taking which in hands Timofey wouldn't be annoyed. Input The first line contains single integer n (2 ≀ n ≀ 105) β€” the number of vertices in the tree. Each of the next n - 1 lines contains two integers u and v (1 ≀ u, v ≀ n, u β‰  v), denoting there is an edge between vertices u and v. It is guaranteed that the given graph is a tree. The next line contains n integers c1, c2, ..., cn (1 ≀ ci ≀ 105), denoting the colors of the vertices. Output Print "NO" in a single line, if Timofey can't take the tree in such a way that it doesn't annoy him. Otherwise print "YES" in the first line. In the second line print the index of the vertex which Timofey should take in hands. If there are multiple answers, print any of them. Examples Input 4 1 2 2 3 3 4 1 2 1 1 Output YES 2 Input 3 1 2 2 3 1 2 3 Output YES 2 Input 4 1 2 2 3 3 4 1 2 1 2 Output NO Submitted 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) col = list(map(int, input().split())) def is_single_color(s, i): vis = set([s]) comp, cur = [s], 0 while cur < len(comp): v = comp[cur] cur += 1 for nv in adj[v]: if nv != i and nv not in vis: vis.add(nv) comp.append(nv) return all(col[v] == col[s] for v in comp) def check(s): if all(is_single_color(v, s) for v in adj[s]): print("YES") print(s + 1) exit() for v in range(n): for nv in adj[v]: if col[nv] != col[v]: check(nv) check(v) print("NO") exit() ```
instruction
0
95,762
13
191,524
No
output
1
95,762
13
191,525
Provide tags and a correct Python 3 solution for this coding contest problem. Danil decided to earn some money, so he had found a part-time job. The interview have went well, so now he is a light switcher. Danil works in a rooted tree (undirected connected acyclic graph) with n vertices, vertex 1 is the root of the tree. There is a room in each vertex, light can be switched on or off in each room. Danil's duties include switching light in all rooms of the subtree of the vertex. It means that if light is switched on in some room of the subtree, he should switch it off. Otherwise, he should switch it on. Unfortunately (or fortunately), Danil is very lazy. He knows that his boss is not going to personally check the work. Instead, he will send Danil tasks using Workforces personal messages. There are two types of tasks: 1. pow v describes a task to switch lights in the subtree of vertex v. 2. get v describes a task to count the number of rooms in the subtree of v, in which the light is turned on. Danil should send the answer to his boss using Workforces messages. A subtree of vertex v is a set of vertices for which the shortest path from them to the root passes through v. In particular, the vertex v is in the subtree of v. Danil is not going to perform his duties. He asks you to write a program, which answers the boss instead of him. Input The first line contains a single integer n (1 ≀ n ≀ 200 000) β€” the number of vertices in the tree. The second line contains n - 1 space-separated integers p2, p3, ..., pn (1 ≀ pi < i), where pi is the ancestor of vertex i. The third line contains n space-separated integers t1, t2, ..., tn (0 ≀ ti ≀ 1), where ti is 1, if the light is turned on in vertex i and 0 otherwise. The fourth line contains a single integer q (1 ≀ q ≀ 200 000) β€” the number of tasks. The next q lines are get v or pow v (1 ≀ v ≀ n) β€” the tasks described above. Output For each task get v print the number of rooms in the subtree of v, in which the light is turned on. Example Input 4 1 1 1 1 0 0 1 9 get 1 get 2 get 3 get 4 pow 1 get 1 get 2 get 3 get 4 Output 2 0 0 1 2 1 1 0 Note <image> The tree before the task pow 1. <image> The tree after the task pow 1.
instruction
0
95,792
13
191,584
Tags: bitmasks, data structures, trees Correct Solution: ``` # ------------------- fast io -------------------- import os import sys from io import BytesIO, IOBase 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") # ------------------- fast io -------------------- from math import ceil def prod(a, mod=10 ** 9 + 7): ans = 1 for each in a: ans = (ans * each) % mod return ans def gcd(x, y): while y: x, y = y, x % y return x def lcm(a, b): return a * b // gcd(a, b) def binary(x, length=16): y = bin(x)[2:] return y if len(y) >= length else "0" * (length - len(y)) + y from math import inf, log2 class LazySegmentTree: def __init__(self, array, func=max): self.n = len(array) self.size = 2 ** (int(log2(self.n - 1)) + 1) if self.n != 1 else 1 self.func = func self.default = 0 self.data = [self.default] * (2 * self.size) self.segsize = [0] * (2 * self.size) self.lazy = [0] * (2 * self.size) self.process(array) def process(self, array): self.data[self.size: self.size + self.n] = array self.segsize[self.size: self.size + self.n] = [1] * len(array) for i in range(self.size - 1, -1, -1): self.data[i] = self.data[2 * i] + self.data[2 * i + 1] self.segsize[i] = self.segsize[2 * i] + self.segsize[2 * i + 1] def push(self, index): """Push the information of the root to it's children!""" self.lazy[2 * index] += self.lazy[index] self.lazy[2 * index + 1] += self.lazy[index] if self.lazy[index] % 2: self.data[index] = self.segsize[index] - self.data[index] self.lazy[index] = 0 def build(self, index): """Build data with the new changes!""" index >>= 1 while index: left, right = self.data[2 * index], self.data[2 * index + 1] if self.lazy[2 * index] % 2: left = self.segsize[2 * index] - left if self.lazy[2 * index + 1] % 2: right = self.segsize[2 * index + 1] - right self.data[index] = left + right index >>= 1 def query(self, alpha, omega): """Returns the result of function over the range (inclusive)!""" res = self.default alpha += self.size omega += self.size + 1 for i in range(len(bin(alpha)[2:]) - 1, 0, -1): self.push(alpha >> i) for i in range(len(bin(omega - 1)[2:]) - 1, 0, -1): self.push((omega - 1) >> i) while alpha < omega: if alpha & 1: if self.lazy[alpha] % 2: res += self.segsize[alpha] - self.data[alpha] else: res += self.data[alpha] alpha += 1 if omega & 1: omega -= 1 if self.lazy[omega] % 2: res += self.segsize[omega] - self.data[omega] else: res += self.data[omega] alpha >>= 1 omega >>= 1 return res def update(self, alpha, omega): """Increases all elements in the range (inclusive) by given value!""" alpha += self.size omega += self.size + 1 l, r = alpha, omega for i in range(len(bin(alpha)[2:]) - 1, 0, -1): self.push(alpha >> i) for i in range(len(bin(omega - 1)[2:]) - 1, 0, -1): self.push((omega - 1) >> i) while alpha < omega: if alpha & 1: self.lazy[alpha] += 1 alpha += 1 if omega & 1: omega -= 1 self.lazy[omega] += 1 alpha >>= 1 omega >>= 1 self.build(l) self.build(r - 1) def dfs(graph, alpha): """Depth First Search on a graph!""" n = len(graph) visited = [False] * n finished = [False] * n dp = [0] * n subtree = [0] * n order = [] stack = [alpha] while stack: v = stack[-1] if not visited[v]: visited[v] = True for u in graph[v]: if not visited[u]: stack.append(u) else: order += [stack.pop()] dp[v] = (switch[v] == 1) subtree[v] = 1 for child in graph[v]: if finished[child]: dp[v] += dp[child] subtree[v] += subtree[child] finished[v] = True return dp, order[::-1], subtree for _ in range(int(input()) if not True else 1): n = int(input()) # n, k = map(int, input().split()) # a, b = map(int, input().split()) # c, d = map(int, input().split()) a = list(map(int, input().split())) switch = [0] + list(map(int, input().split())) # s = input() graph = [[] for i in range(n + 1)] for i in range(len(a)): x, y = i + 2, a[i] graph[x] += [y] graph[y] += [x] dp, order, subtree = dfs(graph, 1) index = [0] * (n + 1) for i in range(len(order)): index[order[i]] = i + 1 st = LazySegmentTree([0] * (n+1), func=lambda a, b: a + b) for i in range(1, n + 1): if switch[i]: st.update(index[i], index[i]) for __ in range(int(input())): s = input().split() x = int(s[1]) count = subtree[x] if s[0] == 'get': print(st.query(index[x], index[x] + count - 1)) else: st.update(index[x], index[x] + count - 1) ```
output
1
95,792
13
191,585
Provide tags and a correct Python 3 solution for this coding contest problem. Danil decided to earn some money, so he had found a part-time job. The interview have went well, so now he is a light switcher. Danil works in a rooted tree (undirected connected acyclic graph) with n vertices, vertex 1 is the root of the tree. There is a room in each vertex, light can be switched on or off in each room. Danil's duties include switching light in all rooms of the subtree of the vertex. It means that if light is switched on in some room of the subtree, he should switch it off. Otherwise, he should switch it on. Unfortunately (or fortunately), Danil is very lazy. He knows that his boss is not going to personally check the work. Instead, he will send Danil tasks using Workforces personal messages. There are two types of tasks: 1. pow v describes a task to switch lights in the subtree of vertex v. 2. get v describes a task to count the number of rooms in the subtree of v, in which the light is turned on. Danil should send the answer to his boss using Workforces messages. A subtree of vertex v is a set of vertices for which the shortest path from them to the root passes through v. In particular, the vertex v is in the subtree of v. Danil is not going to perform his duties. He asks you to write a program, which answers the boss instead of him. Input The first line contains a single integer n (1 ≀ n ≀ 200 000) β€” the number of vertices in the tree. The second line contains n - 1 space-separated integers p2, p3, ..., pn (1 ≀ pi < i), where pi is the ancestor of vertex i. The third line contains n space-separated integers t1, t2, ..., tn (0 ≀ ti ≀ 1), where ti is 1, if the light is turned on in vertex i and 0 otherwise. The fourth line contains a single integer q (1 ≀ q ≀ 200 000) β€” the number of tasks. The next q lines are get v or pow v (1 ≀ v ≀ n) β€” the tasks described above. Output For each task get v print the number of rooms in the subtree of v, in which the light is turned on. Example Input 4 1 1 1 1 0 0 1 9 get 1 get 2 get 3 get 4 pow 1 get 1 get 2 get 3 get 4 Output 2 0 0 1 2 1 1 0 Note <image> The tree before the task pow 1. <image> The tree after the task pow 1.
instruction
0
95,793
13
191,586
Tags: bitmasks, data structures, trees Correct Solution: ``` class LazySegTree: def __init__(self, init_val, seg_ide, lazy_ide, f, g, h): self.n = len(init_val) self.num = 2**(self.n-1).bit_length() self.seg_ide = seg_ide self.lazy_ide = lazy_ide self.f = f #(seg, seg) -> seg self.g = g #(seg, lazy, size) -> seg self.h = h #(lazy, lazy) -> lazy self.seg = [seg_ide]*2*self.num for i in range(self.n): self.seg[i+self.num] = init_val[i] for i in range(self.num-1, 0, -1): self.seg[i] = self.f(self.seg[2*i], self.seg[2*i+1]) self.size = [0]*2*self.num for i in range(self.n): self.size[i+self.num] = 1 for i in range(self.num-1, 0, -1): self.size[i] = self.size[2*i] + self.size[2*i+1] self.lazy = [lazy_ide]*2*self.num def update(self, i, x): i += self.num self.seg[i] = x while i: i = i >> 1 self.seg[i] = self.f(self.seg[2*i], self.seg[2*i+1]) def calc(self, i): return self.g(self.seg[i], self.lazy[i], self.size[i]) def calc_above(self, i): i = i >> 1 while i: self.seg[i] = self.f(self.calc(2*i), self.calc(2*i+1)) i = i >> 1 def propagate(self, i): self.seg[i] = self.g(self.seg[i], self.lazy[i], self.size[i]) self.lazy[2*i] = self.h(self.lazy[2*i], self.lazy[i]) self.lazy[2*i+1] = self.h(self.lazy[2*i+1], self.lazy[i]) self.lazy[i] = self.lazy_ide def propagate_above(self, i): H = i.bit_length() for h in range(H, 0, -1): self.propagate(i >> h) def query(self, l, r): l += self.num r += self.num lm = l // (l & -l) rm = r // (r & -r) -1 self.propagate_above(lm) self.propagate_above(rm) al = self.seg_ide ar = self.seg_ide while l < r: if l & 1: al = self.f(al, self.calc(l)) l += 1 if r & 1: r -= 1 ar = self.f(self.calc(r), ar) l = l >> 1 r = r >> 1 return self.f(al, ar) def oprerate_range(self, l, r, a): l += self.num r += self.num lm = l // (l & -l) rm = r // (r & -r) -1 self.propagate_above(lm) self.propagate_above(rm) while l < r: if l & 1: self.lazy[l] = self.h(self.lazy[l], a) l += 1 if r & 1: r -= 1 self.lazy[r] = self.h(self.lazy[r], a) l = l >> 1 r = r >> 1 self.calc_above(lm) self.calc_above(rm) f = lambda x, y: x+y g = lambda x, a, s: s-x if a%2 == 1 else x h = lambda a, b: a+b def EulerTour(g, root): n = len(g) root = root g = g tank = [root] eulerTour = [] left = [0]*n right = [-1]*n depth = [-1]*n parent = [-1]*n child = [[] for i in range(n)] eulerNum = -1 de = -1 while tank: v = tank.pop() if v >= 0: eulerNum += 1 eulerTour.append(v) left[v] = eulerNum right[v] = eulerNum tank.append(~v) de += 1 depth[v] = de for u in g[v]: if parent[v] == u: continue tank.append(u) parent[u] = v child[v].append(u) else: de -= 1 if ~v != root: eulerTour.append(parent[~v]) eulerNum += 1 right[parent[~v]] = eulerNum return eulerTour, left, right import bisect import sys import io, os input = sys.stdin.readline #input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline def main(): n = int(input()) P = list(map(int, input().split())) T = list(map(int, input().split())) P = [p-1 for p in P] P = [-1]+P edge = [[] for i in range(n)] for i, p in enumerate(P): if p != -1: edge[p].append(i) et, left, right = EulerTour(edge, 0) d = {} B = sorted(left) #print(B) #print(right) for i, b in enumerate(B): d[b] = i A = [0]*n for i in range(n): A[d[left[i]]] = T[i] seg = LazySegTree(A, 0, 0, f, g, h) q = int(input()) for i in range(q): query = list(map(str, input().split())) if query[0] == 'get': u = int(query[1])-1 l = d[left[u]] r = bisect.bisect_right(B, right[u]) print(seg.query(l, r)) else: u = int(query[1])-1 l = d[left[u]] r = bisect.bisect_right(B, right[u]) seg.oprerate_range(l, r, 1) if __name__ == '__main__': main() ```
output
1
95,793
13
191,587
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Danil decided to earn some money, so he had found a part-time job. The interview have went well, so now he is a light switcher. Danil works in a rooted tree (undirected connected acyclic graph) with n vertices, vertex 1 is the root of the tree. There is a room in each vertex, light can be switched on or off in each room. Danil's duties include switching light in all rooms of the subtree of the vertex. It means that if light is switched on in some room of the subtree, he should switch it off. Otherwise, he should switch it on. Unfortunately (or fortunately), Danil is very lazy. He knows that his boss is not going to personally check the work. Instead, he will send Danil tasks using Workforces personal messages. There are two types of tasks: 1. pow v describes a task to switch lights in the subtree of vertex v. 2. get v describes a task to count the number of rooms in the subtree of v, in which the light is turned on. Danil should send the answer to his boss using Workforces messages. A subtree of vertex v is a set of vertices for which the shortest path from them to the root passes through v. In particular, the vertex v is in the subtree of v. Danil is not going to perform his duties. He asks you to write a program, which answers the boss instead of him. Input The first line contains a single integer n (1 ≀ n ≀ 200 000) β€” the number of vertices in the tree. The second line contains n - 1 space-separated integers p2, p3, ..., pn (1 ≀ pi < i), where pi is the ancestor of vertex i. The third line contains n space-separated integers t1, t2, ..., tn (0 ≀ ti ≀ 1), where ti is 1, if the light is turned on in vertex i and 0 otherwise. The fourth line contains a single integer q (1 ≀ q ≀ 200 000) β€” the number of tasks. The next q lines are get v or pow v (1 ≀ v ≀ n) β€” the tasks described above. Output For each task get v print the number of rooms in the subtree of v, in which the light is turned on. Example Input 4 1 1 1 1 0 0 1 9 get 1 get 2 get 3 get 4 pow 1 get 1 get 2 get 3 get 4 Output 2 0 0 1 2 1 1 0 Note <image> The tree before the task pow 1. <image> The tree after the task pow 1. Submitted Solution: ``` n=int(input()) par=[int(i)-1 for i in input().split()] t=list(map(int,input().split())) qq=int(input()) tr=[[] for i in range(n)] for i in range(n-1): tr[par[i]].append(i+1) size=[1 for i in range(n)] on=[t[i] for i in range(n)] pos=[-1 for i in range(n)] m=[] i=0 s=[0] while s: x=s.pop() m.append(x) pos[x]=i i+=1 for y in tr[x]: if pos[y]!=-1:continue s.append(y) for i in range(n-1,0,-1): j=m[i] size[par[j-1]]+=size[j] on[par[j-1]]+=on[j] it=[0 for i in range(2*n)] def u(i,v): i+=n it[i]+=v while i>0: i>>=1 it[i]=it[i<<1]+it[i<<1|1] def q(i): l=n r=i+n+1 ans=0 while l<r: if l&1: ans+=it[l] l+=1 if r&1: r-=1 ans+=it[r] r>>=1 l>>=1 return(ans) for _ in range(qq): s=str(input()) v=int(s[-1])-1 i=pos[v] if s[0]=='g': if q(i)%2==0: print(on[v]) else: print(size[v]-on[v]) else: j=i+size[v] u(i,1) if j<n: u(j,-1) ```
instruction
0
95,794
13
191,588
No
output
1
95,794
13
191,589
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Danil decided to earn some money, so he had found a part-time job. The interview have went well, so now he is a light switcher. Danil works in a rooted tree (undirected connected acyclic graph) with n vertices, vertex 1 is the root of the tree. There is a room in each vertex, light can be switched on or off in each room. Danil's duties include switching light in all rooms of the subtree of the vertex. It means that if light is switched on in some room of the subtree, he should switch it off. Otherwise, he should switch it on. Unfortunately (or fortunately), Danil is very lazy. He knows that his boss is not going to personally check the work. Instead, he will send Danil tasks using Workforces personal messages. There are two types of tasks: 1. pow v describes a task to switch lights in the subtree of vertex v. 2. get v describes a task to count the number of rooms in the subtree of v, in which the light is turned on. Danil should send the answer to his boss using Workforces messages. A subtree of vertex v is a set of vertices for which the shortest path from them to the root passes through v. In particular, the vertex v is in the subtree of v. Danil is not going to perform his duties. He asks you to write a program, which answers the boss instead of him. Input The first line contains a single integer n (1 ≀ n ≀ 200 000) β€” the number of vertices in the tree. The second line contains n - 1 space-separated integers p2, p3, ..., pn (1 ≀ pi < i), where pi is the ancestor of vertex i. The third line contains n space-separated integers t1, t2, ..., tn (0 ≀ ti ≀ 1), where ti is 1, if the light is turned on in vertex i and 0 otherwise. The fourth line contains a single integer q (1 ≀ q ≀ 200 000) β€” the number of tasks. The next q lines are get v or pow v (1 ≀ v ≀ n) β€” the tasks described above. Output For each task get v print the number of rooms in the subtree of v, in which the light is turned on. Example Input 4 1 1 1 1 0 0 1 9 get 1 get 2 get 3 get 4 pow 1 get 1 get 2 get 3 get 4 Output 2 0 0 1 2 1 1 0 Note <image> The tree before the task pow 1. <image> The tree after the task pow 1. Submitted Solution: ``` class Node: def __init__(self): self.parent = None self.children = [] self.on = False self.count = 0 def toggle(self): self.on = not self.on diff = 1 if self.on else -1 for child in self.children: diff += child.toggle() self.count += diff return diff def calc_count(self): c = 0 for child in self.children: child.calc_count() c += child.count self.count = c+1 if self.on else c nodes = [] v = int(input()) for i in range(v): nodes.append(Node()) p = list(map(int, input().split())) for i in range(len(p)): nodes[i+1].parent = nodes[p[i]-1] nodes[p[i]-1].children.append(nodes[i+1]) t = list(input().split()) for i in range(len(t)): nodes[i].on = t[i] == '1' nodes[0].calc_count() q = int(input()) for i in range(q): command, v = input().split() v = int(v) - 1 if command == 'pow': nodes[v].toggle() if command == 'get': print(nodes[v].count) ```
instruction
0
95,795
13
191,590
No
output
1
95,795
13
191,591
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Danil decided to earn some money, so he had found a part-time job. The interview have went well, so now he is a light switcher. Danil works in a rooted tree (undirected connected acyclic graph) with n vertices, vertex 1 is the root of the tree. There is a room in each vertex, light can be switched on or off in each room. Danil's duties include switching light in all rooms of the subtree of the vertex. It means that if light is switched on in some room of the subtree, he should switch it off. Otherwise, he should switch it on. Unfortunately (or fortunately), Danil is very lazy. He knows that his boss is not going to personally check the work. Instead, he will send Danil tasks using Workforces personal messages. There are two types of tasks: 1. pow v describes a task to switch lights in the subtree of vertex v. 2. get v describes a task to count the number of rooms in the subtree of v, in which the light is turned on. Danil should send the answer to his boss using Workforces messages. A subtree of vertex v is a set of vertices for which the shortest path from them to the root passes through v. In particular, the vertex v is in the subtree of v. Danil is not going to perform his duties. He asks you to write a program, which answers the boss instead of him. Input The first line contains a single integer n (1 ≀ n ≀ 200 000) β€” the number of vertices in the tree. The second line contains n - 1 space-separated integers p2, p3, ..., pn (1 ≀ pi < i), where pi is the ancestor of vertex i. The third line contains n space-separated integers t1, t2, ..., tn (0 ≀ ti ≀ 1), where ti is 1, if the light is turned on in vertex i and 0 otherwise. The fourth line contains a single integer q (1 ≀ q ≀ 200 000) β€” the number of tasks. The next q lines are get v or pow v (1 ≀ v ≀ n) β€” the tasks described above. Output For each task get v print the number of rooms in the subtree of v, in which the light is turned on. Example Input 4 1 1 1 1 0 0 1 9 get 1 get 2 get 3 get 4 pow 1 get 1 get 2 get 3 get 4 Output 2 0 0 1 2 1 1 0 Note <image> The tree before the task pow 1. <image> The tree after the task pow 1. Submitted Solution: ``` class Node: def __init__(self): self.parent = None self.on = False self.children = [] self.count = -1 def toggle(self): self.on = not self.on count = 0 for child in self.children: child.toggle() count += child.count self.count = count+1 if self.on else count def calc_count(self): if self.count != -1: return self.count count = 0 for child in self.children: child.calc_count() count += child.count self.count = count+1 if self.on else count nodes = [] v = int(input()) for i in range(v): nodes.append(Node()) p = list(map(int, input().split())) for i in range(len(p)): nodes[i+1].parent = nodes[p[i]-1] nodes[p[i]-1].children.append(nodes[i+1]) t = list(map(int, input().split())) for i in range(len(t)): nodes[i].on = t[i] == 1 for i in range(v): nodes[i].calc_count() q = int(input()) for i in range(q): command, v = input().split() v = int(v) - 1 if command == 'pow': nodes[v].toggle() if command == 'get': print(nodes[v].count) ```
instruction
0
95,796
13
191,592
No
output
1
95,796
13
191,593
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Danil decided to earn some money, so he had found a part-time job. The interview have went well, so now he is a light switcher. Danil works in a rooted tree (undirected connected acyclic graph) with n vertices, vertex 1 is the root of the tree. There is a room in each vertex, light can be switched on or off in each room. Danil's duties include switching light in all rooms of the subtree of the vertex. It means that if light is switched on in some room of the subtree, he should switch it off. Otherwise, he should switch it on. Unfortunately (or fortunately), Danil is very lazy. He knows that his boss is not going to personally check the work. Instead, he will send Danil tasks using Workforces personal messages. There are two types of tasks: 1. pow v describes a task to switch lights in the subtree of vertex v. 2. get v describes a task to count the number of rooms in the subtree of v, in which the light is turned on. Danil should send the answer to his boss using Workforces messages. A subtree of vertex v is a set of vertices for which the shortest path from them to the root passes through v. In particular, the vertex v is in the subtree of v. Danil is not going to perform his duties. He asks you to write a program, which answers the boss instead of him. Input The first line contains a single integer n (1 ≀ n ≀ 200 000) β€” the number of vertices in the tree. The second line contains n - 1 space-separated integers p2, p3, ..., pn (1 ≀ pi < i), where pi is the ancestor of vertex i. The third line contains n space-separated integers t1, t2, ..., tn (0 ≀ ti ≀ 1), where ti is 1, if the light is turned on in vertex i and 0 otherwise. The fourth line contains a single integer q (1 ≀ q ≀ 200 000) β€” the number of tasks. The next q lines are get v or pow v (1 ≀ v ≀ n) β€” the tasks described above. Output For each task get v print the number of rooms in the subtree of v, in which the light is turned on. Example Input 4 1 1 1 1 0 0 1 9 get 1 get 2 get 3 get 4 pow 1 get 1 get 2 get 3 get 4 Output 2 0 0 1 2 1 1 0 Note <image> The tree before the task pow 1. <image> The tree after the task pow 1. Submitted Solution: ``` # ------------------- fast io -------------------- import os import sys from io import BytesIO, IOBase 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") # ------------------- fast io -------------------- from math import ceil def prod(a, mod=10 ** 9 + 7): ans = 1 for each in a: ans = (ans * each) % mod return ans def gcd(x, y): while y: x, y = y, x % y return x def lcm(a, b): return a * b // gcd(a, b) def binary(x, length=16): y = bin(x)[2:] return y if len(y) >= length else "0" * (length - len(y)) + y from math import inf, log2 class LazySegmentTree: def __init__(self, array, func=max): self.n = len(array) self.size = 2 ** (int(log2(self.n - 1)) + 1) if self.n != 1 else 1 self.func = func self.default = 0 self.data = [self.default] * (2 * self.size) self.segsize = [0] * (2 * self.size) self.lazy = [0] * (2 * self.size) self.process(array) def process(self, array): self.data[self.size: self.size + self.n] = array self.segsize[self.size: self.size + self.n] = [1] * len(array) for i in range(self.size - 1, -1, -1): self.data[i] = self.data[2 * i] + self.data[2 * i + 1] self.segsize[i] = self.segsize[2 * i] + self.segsize[2 * i + 1] def push(self, index): """Push the information of the root to it's children!""" self.lazy[2 * index] += self.lazy[index] self.lazy[2 * index + 1] += self.lazy[index] if self.lazy[index] % 2: self.data[index] = self.segsize[index] - self.data[index] self.lazy[index] = 0 def build(self, index): """Build data with the new changes!""" index >>= 1 while index: left, right = self.data[2 * index], self.data[2 * index + 1] if self.lazy[2 * index] % 2: left = self.segsize[2 * index] - left if self.lazy[2 * index + 1] % 2: right = self.segsize[2 * index + 1] - right self.data[index] = left + right index >>= 1 def query(self, alpha, omega): """Returns the result of function over the range (inclusive)!""" res = self.default alpha += self.size omega += self.size + 1 for i in range(len(bin(alpha)[2:]) - 1, 0, -1): self.push(alpha >> i) for i in range(len(bin(omega - 1)[2:]) - 1, 0, -1): self.push((omega - 1) >> i) while alpha < omega: if alpha & 1: if self.lazy[alpha] % 2: res += self.segsize[alpha] - self.data[alpha] else: res += self.data[alpha] alpha += 1 if omega & 1: omega -= 1 if self.lazy[omega] % 2: res += self.segsize[omega] - self.data[omega] else: res += self.data[omega] alpha >>= 1 omega >>= 1 return res def update(self, alpha, omega): """Increases all elements in the range (inclusive) by given value!""" alpha += self.size omega += self.size + 1 l, r = alpha, omega for i in range(len(bin(alpha)[2:]) - 1, 0, -1): self.push(alpha >> i) for i in range(len(bin(omega - 1)[2:]) - 1, 0, -1): self.push((omega - 1) >> i) while alpha < omega: if alpha & 1: self.lazy[alpha] += 1 alpha += 1 if omega & 1: omega -= 1 self.lazy[omega] += 1 alpha >>= 1 omega >>= 1 self.build(l) self.build(r - 1) def dfs(graph, alpha): """Depth First Search on a graph!""" n = len(graph) visited = [False] * n finished = [False] * n dp = [0] * n subtree = [0] * n order = [] stack = [alpha] while stack: v = stack[-1] if not visited[v]: visited[v] = True for u in graph[v]: if not visited[u]: stack.append(u) else: order += [stack.pop()] dp[v] = (switch[v] == 1) subtree[v] = 1 for child in graph[v]: if finished[child]: dp[v] += dp[child] subtree[v] += subtree[child] finished[v] = True return dp, order[::-1], subtree for _ in range(int(input()) if not True else 1): n = int(input()) # n, k = map(int, input().split()) # a, b = map(int, input().split()) # c, d = map(int, input().split()) a = list(map(int, input().split())) switch = [0] + list(map(int, input().split())) # s = input() graph = [[] for i in range(n + 1)] for i in range(len(a)): x, y = i + 2, a[i] graph[x] += [y] graph[y] += [x] dp, order, subtree = dfs(graph, 1) index = [0] * (n + 1) for i in range(len(order)): index[order[i]] = i + 1 st = LazySegmentTree(switch, func=lambda a, b: a + b) #for i in range(1, n + 1): # if switch[i]: # st.update(index[i], i) for __ in range(int(input())): s = input().split() x = int(s[1]) count = subtree[x] if s[0] == 'get': print(st.query(index[x], index[x] + count - 1)) else: st.update(index[x], index[x] + count - 1) ```
instruction
0
95,797
13
191,594
No
output
1
95,797
13
191,595
Provide tags and a correct Python 3 solution for this coding contest problem. Sasha is taking part in a programming competition. In one of the problems she should check if some rooted trees are isomorphic or not. She has never seen this problem before, but, being an experienced participant, she guessed that she should match trees to some sequences and then compare these sequences instead of trees. Sasha wants to match each tree with a sequence a0, a1, ..., ah, where h is the height of the tree, and ai equals to the number of vertices that are at distance of i edges from root. Unfortunately, this time Sasha's intuition was wrong, and there could be several trees matching the same sequence. To show it, you need to write a program that, given the sequence ai, builds two non-isomorphic rooted trees that match that sequence, or determines that there is only one such tree. Two rooted trees are isomorphic, if you can reenumerate the vertices of the first one in such a way, that the index of the root becomes equal the index of the root of the second tree, and these two trees become equal. The height of a rooted tree is the maximum number of edges on a path from the root to any other vertex. Input The first line contains a single integer h (2 ≀ h ≀ 105) β€” the height of the tree. The second line contains h + 1 integers β€” the sequence a0, a1, ..., ah (1 ≀ ai ≀ 2Β·105). The sum of all ai does not exceed 2Β·105. It is guaranteed that there is at least one tree matching this sequence. Output If there is only one tree matching this sequence, print "perfect". Otherwise print "ambiguous" in the first line. In the second and in the third line print descriptions of two trees in the following format: in one line print <image> integers, the k-th of them should be the parent of vertex k or be equal to zero, if the k-th vertex is the root. These treese should be non-isomorphic and should match the given sequence. Examples Input 2 1 1 1 Output perfect Input 2 1 2 2 Output ambiguous 0 1 1 3 3 0 1 1 3 2 Note The only tree in the first example and the two printed trees from the second example are shown on the picture: <image>
instruction
0
95,798
13
191,596
Tags: constructive algorithms, trees Correct Solution: ``` ''' =============================== -- @uthor : Kaleab Asfaw -- Handle : Kaleab_Asfaw -- Bio : High-School Student ===============================''' # Fast IO import sys import os from io import BytesIO, IOBase 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") # Others # from math import floor, ceil, gcd # from decimal import Decimal as d mod = 10**9+7 def lcm(x, y): return (x * y) / (gcd(x, y)) def fact(x, mod=mod): ans = 1 for i in range(1, x+1): ans = (ans * i) % mod return ans def arr2D(n, m, default=0): return [[default for j in range(m)] for i in range(n)] def arr3D(n, m, r, default=0): return [[[default for k in range(r)] for j in range(m)] for i in range(n)] def sortDictV(x): return {k: v for k, v in sorted(x.items(), key = lambda item : item[1])} class DSU: def __init__(self, length): self.length = length; self.parent = [-1] * self.length # O(log(n)) def getParent(self, node, start): # O(log(n)) if node >= self.length: return False if self.parent[node] < 0: if start != node: self.parent[start] = node return node return self.getParent(self.parent[node], start) def union(self, node1, node2): # O(log(n)) parent1 = self.getParent(node1, node1); parent2 = self.getParent(node2, node2) if parent1 == parent2: return False elif self.parent[parent1] <= self.parent[parent2]: self.parent[parent1] += self.parent[parent2]; self.parent[parent2] = parent1 else: self.parent[parent2] += self.parent[parent1]; self.parent[parent1] = parent2 return True def getCount(self, node): return -self.parent[self.getParent(node, node)] # O(log(n)) def exact(num): if abs(num - round(num)) <= 10**(-9):return round(num) return num def solve(n, lst): get = False ind = -1 for i in range(n): if lst[i] > 1 and lst[i+1] > 1: get = True ind = i break if get: print("ambiguous") pre = [lst[0]] for i in lst[1:]: pre.append(pre[-1] + i) ans1 = [0] for i in range(lst[1]): ans1.append(1) prei = 0 for i in lst[2:]: ans1 += [pre[prei] + 1] * i prei += 1 print(" ".join(list(map(str, ans1)))) val = pre[ind] + 1 if val in ans1: for i in range(len(ans1)): if ans1[i] == val: ans1[i-1] += 1 else: ans1[-1] += 1 return " ".join(list(map(str, ans1))) else: return "perfect" n = int(input()) lst = list(map(int, input().split())) print(solve(n, lst)) ```
output
1
95,798
13
191,597
Provide tags and a correct Python 3 solution for this coding contest problem. Sasha is taking part in a programming competition. In one of the problems she should check if some rooted trees are isomorphic or not. She has never seen this problem before, but, being an experienced participant, she guessed that she should match trees to some sequences and then compare these sequences instead of trees. Sasha wants to match each tree with a sequence a0, a1, ..., ah, where h is the height of the tree, and ai equals to the number of vertices that are at distance of i edges from root. Unfortunately, this time Sasha's intuition was wrong, and there could be several trees matching the same sequence. To show it, you need to write a program that, given the sequence ai, builds two non-isomorphic rooted trees that match that sequence, or determines that there is only one such tree. Two rooted trees are isomorphic, if you can reenumerate the vertices of the first one in such a way, that the index of the root becomes equal the index of the root of the second tree, and these two trees become equal. The height of a rooted tree is the maximum number of edges on a path from the root to any other vertex. Input The first line contains a single integer h (2 ≀ h ≀ 105) β€” the height of the tree. The second line contains h + 1 integers β€” the sequence a0, a1, ..., ah (1 ≀ ai ≀ 2Β·105). The sum of all ai does not exceed 2Β·105. It is guaranteed that there is at least one tree matching this sequence. Output If there is only one tree matching this sequence, print "perfect". Otherwise print "ambiguous" in the first line. In the second and in the third line print descriptions of two trees in the following format: in one line print <image> integers, the k-th of them should be the parent of vertex k or be equal to zero, if the k-th vertex is the root. These treese should be non-isomorphic and should match the given sequence. Examples Input 2 1 1 1 Output perfect Input 2 1 2 2 Output ambiguous 0 1 1 3 3 0 1 1 3 2 Note The only tree in the first example and the two printed trees from the second example are shown on the picture: <image>
instruction
0
95,799
13
191,598
Tags: constructive algorithms, trees Correct Solution: ``` #Abhigyan Khaund - syl n = int(input()) a = list(map(int, input().split())) ambi = 0 for i in range(1,len(a)): if(a[i]>1 and a[i-1]>1): ambi = 1 ans1 = "" ans2 = "" if(ambi == 0): print ("perfect") else: print ("ambiguous") ans1+="0 " k = 0 s = sum(a) j = 1 h = 1 c = 0 st = 2 ans2+= "0" + " " k1 = 0 # s = sum(a) j1 = 1 h1 = 1 c1 = 0 st1 = 2 prev_st1 = 1 for i in range(1,s): # print j, ans1+= str(j) + " " ans2+= str(j1) + " " k+=1 c+=1 if(c>=a[h]): k = 0 h+=1 c = 0 j = st st = i+2 k1+=1 if(k1==1): k1 = 0 j1+=1 c1+=1 if(c1>=a[h1-1]): j1 = prev_st1 k1 = 0 if(c1>=a[h1]): k1 = 0 h1+=1 c1 = 0 j1 = st1 prev_st1 = st1 st1 = i+2 # print # print print (ans1) print (ans2) ```
output
1
95,799
13
191,599
Provide tags and a correct Python 3 solution for this coding contest problem. Sasha is taking part in a programming competition. In one of the problems she should check if some rooted trees are isomorphic or not. She has never seen this problem before, but, being an experienced participant, she guessed that she should match trees to some sequences and then compare these sequences instead of trees. Sasha wants to match each tree with a sequence a0, a1, ..., ah, where h is the height of the tree, and ai equals to the number of vertices that are at distance of i edges from root. Unfortunately, this time Sasha's intuition was wrong, and there could be several trees matching the same sequence. To show it, you need to write a program that, given the sequence ai, builds two non-isomorphic rooted trees that match that sequence, or determines that there is only one such tree. Two rooted trees are isomorphic, if you can reenumerate the vertices of the first one in such a way, that the index of the root becomes equal the index of the root of the second tree, and these two trees become equal. The height of a rooted tree is the maximum number of edges on a path from the root to any other vertex. Input The first line contains a single integer h (2 ≀ h ≀ 105) β€” the height of the tree. The second line contains h + 1 integers β€” the sequence a0, a1, ..., ah (1 ≀ ai ≀ 2Β·105). The sum of all ai does not exceed 2Β·105. It is guaranteed that there is at least one tree matching this sequence. Output If there is only one tree matching this sequence, print "perfect". Otherwise print "ambiguous" in the first line. In the second and in the third line print descriptions of two trees in the following format: in one line print <image> integers, the k-th of them should be the parent of vertex k or be equal to zero, if the k-th vertex is the root. These treese should be non-isomorphic and should match the given sequence. Examples Input 2 1 1 1 Output perfect Input 2 1 2 2 Output ambiguous 0 1 1 3 3 0 1 1 3 2 Note The only tree in the first example and the two printed trees from the second example are shown on the picture: <image>
instruction
0
95,800
13
191,600
Tags: constructive algorithms, trees Correct Solution: ``` import sys #f = open('input', 'r') f = sys.stdin n = f.readline() n = int(n) cl = f.readline().split() cl = [int(x) for x in cl] c_index = 0 p1 = ['0'] p2 = ['0'] ambiguous = False cur_index = 1 for i, c in enumerate(cl): if i == 0: continue if i > 0 and cl[i-1] > 1 and c > 1: ambiguous = True p1 += [str(cur_index)] * c p2 += [str(cur_index-1)] + [str(cur_index)] * (c-1) else: p1 += [str(cur_index)] * c p2 += [str(cur_index)] * c cur_index += c if ambiguous: print('ambiguous') print(' '.join(p1)) print(' '.join(p2)) else: print('perfect') ```
output
1
95,800
13
191,601
Provide tags and a correct Python 3 solution for this coding contest problem. Sasha is taking part in a programming competition. In one of the problems she should check if some rooted trees are isomorphic or not. She has never seen this problem before, but, being an experienced participant, she guessed that she should match trees to some sequences and then compare these sequences instead of trees. Sasha wants to match each tree with a sequence a0, a1, ..., ah, where h is the height of the tree, and ai equals to the number of vertices that are at distance of i edges from root. Unfortunately, this time Sasha's intuition was wrong, and there could be several trees matching the same sequence. To show it, you need to write a program that, given the sequence ai, builds two non-isomorphic rooted trees that match that sequence, or determines that there is only one such tree. Two rooted trees are isomorphic, if you can reenumerate the vertices of the first one in such a way, that the index of the root becomes equal the index of the root of the second tree, and these two trees become equal. The height of a rooted tree is the maximum number of edges on a path from the root to any other vertex. Input The first line contains a single integer h (2 ≀ h ≀ 105) β€” the height of the tree. The second line contains h + 1 integers β€” the sequence a0, a1, ..., ah (1 ≀ ai ≀ 2Β·105). The sum of all ai does not exceed 2Β·105. It is guaranteed that there is at least one tree matching this sequence. Output If there is only one tree matching this sequence, print "perfect". Otherwise print "ambiguous" in the first line. In the second and in the third line print descriptions of two trees in the following format: in one line print <image> integers, the k-th of them should be the parent of vertex k or be equal to zero, if the k-th vertex is the root. These treese should be non-isomorphic and should match the given sequence. Examples Input 2 1 1 1 Output perfect Input 2 1 2 2 Output ambiguous 0 1 1 3 3 0 1 1 3 2 Note The only tree in the first example and the two printed trees from the second example are shown on the picture: <image>
instruction
0
95,801
13
191,602
Tags: constructive algorithms, trees Correct Solution: ``` n = int(input()) fl = 1 a = [int(x) for x in input().split()] for i in range(1,n+1): if a[i] > 1 and a[i-1] > 1: fl = 0 break if fl == 1: print("perfect") else : print("ambiguous") print("0", end=" ") cnt=1 x=1 fl=1 for i in range(1,n+1): for j in range(a[i]): print(cnt,end=" ") x += 1 cnt=x print() print("0", end=" ") cnt=1 x=1 fl=1 for i in range(1,n+1): if a[i] > 1 and a[i-1] > 1 and fl == 1: fl = 0 for j in range(a[i]-1): print(cnt, end=" ") x += 1 print(cnt-1,end=" ") x += 1 else: for j in range(a[i]): print(cnt,end=" ") x += 1 cnt=x ```
output
1
95,801
13
191,603
Provide tags and a correct Python 3 solution for this coding contest problem. Sasha is taking part in a programming competition. In one of the problems she should check if some rooted trees are isomorphic or not. She has never seen this problem before, but, being an experienced participant, she guessed that she should match trees to some sequences and then compare these sequences instead of trees. Sasha wants to match each tree with a sequence a0, a1, ..., ah, where h is the height of the tree, and ai equals to the number of vertices that are at distance of i edges from root. Unfortunately, this time Sasha's intuition was wrong, and there could be several trees matching the same sequence. To show it, you need to write a program that, given the sequence ai, builds two non-isomorphic rooted trees that match that sequence, or determines that there is only one such tree. Two rooted trees are isomorphic, if you can reenumerate the vertices of the first one in such a way, that the index of the root becomes equal the index of the root of the second tree, and these two trees become equal. The height of a rooted tree is the maximum number of edges on a path from the root to any other vertex. Input The first line contains a single integer h (2 ≀ h ≀ 105) β€” the height of the tree. The second line contains h + 1 integers β€” the sequence a0, a1, ..., ah (1 ≀ ai ≀ 2Β·105). The sum of all ai does not exceed 2Β·105. It is guaranteed that there is at least one tree matching this sequence. Output If there is only one tree matching this sequence, print "perfect". Otherwise print "ambiguous" in the first line. In the second and in the third line print descriptions of two trees in the following format: in one line print <image> integers, the k-th of them should be the parent of vertex k or be equal to zero, if the k-th vertex is the root. These treese should be non-isomorphic and should match the given sequence. Examples Input 2 1 1 1 Output perfect Input 2 1 2 2 Output ambiguous 0 1 1 3 3 0 1 1 3 2 Note The only tree in the first example and the two printed trees from the second example are shown on the picture: <image>
instruction
0
95,802
13
191,604
Tags: constructive algorithms, trees Correct Solution: ``` def print_iso(nnodes, counter): print("ambiguous") final_tree1 = [] final_tree2 = [] c = 0 parent = 0 for n in nnodes: if c != counter: for i in range(0, n): final_tree1.append(parent) final_tree2.append(parent) else: final_tree1.append(parent - 1) final_tree2.append(parent) for i in range(0, n-1): final_tree1.append(parent) final_tree2.append(parent) parent += n c += 1 final_tree1 = [str(i) for i in final_tree1] final_tree2 = [str(i) for i in final_tree2] print(' '.join(final_tree1)) print(' '.join(final_tree2)) def main(): height = int(input()) nnodes = input() nnodes = nnodes.split(' ') nnodes = [int(i) for i in nnodes] perfect = True prev = 1 counter = 0; for n in nnodes: if n > 1 and prev > 1: print_iso(nnodes, counter) perfect = False break prev = n counter += 1 if perfect: print("perfect") if __name__ == "__main__": main() ```
output
1
95,802
13
191,605
Provide tags and a correct Python 3 solution for this coding contest problem. Sasha is taking part in a programming competition. In one of the problems she should check if some rooted trees are isomorphic or not. She has never seen this problem before, but, being an experienced participant, she guessed that she should match trees to some sequences and then compare these sequences instead of trees. Sasha wants to match each tree with a sequence a0, a1, ..., ah, where h is the height of the tree, and ai equals to the number of vertices that are at distance of i edges from root. Unfortunately, this time Sasha's intuition was wrong, and there could be several trees matching the same sequence. To show it, you need to write a program that, given the sequence ai, builds two non-isomorphic rooted trees that match that sequence, or determines that there is only one such tree. Two rooted trees are isomorphic, if you can reenumerate the vertices of the first one in such a way, that the index of the root becomes equal the index of the root of the second tree, and these two trees become equal. The height of a rooted tree is the maximum number of edges on a path from the root to any other vertex. Input The first line contains a single integer h (2 ≀ h ≀ 105) β€” the height of the tree. The second line contains h + 1 integers β€” the sequence a0, a1, ..., ah (1 ≀ ai ≀ 2Β·105). The sum of all ai does not exceed 2Β·105. It is guaranteed that there is at least one tree matching this sequence. Output If there is only one tree matching this sequence, print "perfect". Otherwise print "ambiguous" in the first line. In the second and in the third line print descriptions of two trees in the following format: in one line print <image> integers, the k-th of them should be the parent of vertex k or be equal to zero, if the k-th vertex is the root. These treese should be non-isomorphic and should match the given sequence. Examples Input 2 1 1 1 Output perfect Input 2 1 2 2 Output ambiguous 0 1 1 3 3 0 1 1 3 2 Note The only tree in the first example and the two printed trees from the second example are shown on the picture: <image>
instruction
0
95,803
13
191,606
Tags: constructive algorithms, trees Correct Solution: ``` n = int(input()) h = [int(i) for i in input().split()] flag = 0 for i in range(n): if h[i] >= 2 and h[i+1] >= 2: flag = i if flag: a = [] c = 0 for i in range(n+1): for j in range(h[i]): a.append(c) c += h[i] b = [] c = 0 for i in range(n+1): for j in range(h[i]): if i == flag+1 and j == 0: b.append(c-1) else: b.append(c) c += h[i] print("ambiguous") print(" ".join([str(i) for i in a])) print(" ".join([str(i) for i in b])) else: print("perfect") ```
output
1
95,803
13
191,607
Provide tags and a correct Python 3 solution for this coding contest problem. Sasha is taking part in a programming competition. In one of the problems she should check if some rooted trees are isomorphic or not. She has never seen this problem before, but, being an experienced participant, she guessed that she should match trees to some sequences and then compare these sequences instead of trees. Sasha wants to match each tree with a sequence a0, a1, ..., ah, where h is the height of the tree, and ai equals to the number of vertices that are at distance of i edges from root. Unfortunately, this time Sasha's intuition was wrong, and there could be several trees matching the same sequence. To show it, you need to write a program that, given the sequence ai, builds two non-isomorphic rooted trees that match that sequence, or determines that there is only one such tree. Two rooted trees are isomorphic, if you can reenumerate the vertices of the first one in such a way, that the index of the root becomes equal the index of the root of the second tree, and these two trees become equal. The height of a rooted tree is the maximum number of edges on a path from the root to any other vertex. Input The first line contains a single integer h (2 ≀ h ≀ 105) β€” the height of the tree. The second line contains h + 1 integers β€” the sequence a0, a1, ..., ah (1 ≀ ai ≀ 2Β·105). The sum of all ai does not exceed 2Β·105. It is guaranteed that there is at least one tree matching this sequence. Output If there is only one tree matching this sequence, print "perfect". Otherwise print "ambiguous" in the first line. In the second and in the third line print descriptions of two trees in the following format: in one line print <image> integers, the k-th of them should be the parent of vertex k or be equal to zero, if the k-th vertex is the root. These treese should be non-isomorphic and should match the given sequence. Examples Input 2 1 1 1 Output perfect Input 2 1 2 2 Output ambiguous 0 1 1 3 3 0 1 1 3 2 Note The only tree in the first example and the two printed trees from the second example are shown on the picture: <image>
instruction
0
95,804
13
191,608
Tags: constructive algorithms, trees Correct Solution: ``` h = int( input() ) nums = [int(x) for x in input().split()] if not any([nums[i] > 1 and nums[i+1] > 1 for i in range(h)]): print('perfect') else: print('ambiguous') # tree 1 cur = 1 flag = False print(0, end=' ') for l in range(1, h+1): [print(cur, end=' ') for i in range(nums[l])] cur += nums[l] print() # tree 2 cur = 1 flag = False print(0, end=' ') for l in range(1, h+1): if not flag and nums[l] > 1 and nums[l-1] > 1: # can be different here! flag = True print(cur-1, end=' ') [print(cur, end=' ') for i in range(nums[l]-1)] else: [print(cur, end=' ') for i in range(nums[l])] cur += nums[l] ```
output
1
95,804
13
191,609
Provide tags and a correct Python 3 solution for this coding contest problem. Sasha is taking part in a programming competition. In one of the problems she should check if some rooted trees are isomorphic or not. She has never seen this problem before, but, being an experienced participant, she guessed that she should match trees to some sequences and then compare these sequences instead of trees. Sasha wants to match each tree with a sequence a0, a1, ..., ah, where h is the height of the tree, and ai equals to the number of vertices that are at distance of i edges from root. Unfortunately, this time Sasha's intuition was wrong, and there could be several trees matching the same sequence. To show it, you need to write a program that, given the sequence ai, builds two non-isomorphic rooted trees that match that sequence, or determines that there is only one such tree. Two rooted trees are isomorphic, if you can reenumerate the vertices of the first one in such a way, that the index of the root becomes equal the index of the root of the second tree, and these two trees become equal. The height of a rooted tree is the maximum number of edges on a path from the root to any other vertex. Input The first line contains a single integer h (2 ≀ h ≀ 105) β€” the height of the tree. The second line contains h + 1 integers β€” the sequence a0, a1, ..., ah (1 ≀ ai ≀ 2Β·105). The sum of all ai does not exceed 2Β·105. It is guaranteed that there is at least one tree matching this sequence. Output If there is only one tree matching this sequence, print "perfect". Otherwise print "ambiguous" in the first line. In the second and in the third line print descriptions of two trees in the following format: in one line print <image> integers, the k-th of them should be the parent of vertex k or be equal to zero, if the k-th vertex is the root. These treese should be non-isomorphic and should match the given sequence. Examples Input 2 1 1 1 Output perfect Input 2 1 2 2 Output ambiguous 0 1 1 3 3 0 1 1 3 2 Note The only tree in the first example and the two printed trees from the second example are shown on the picture: <image>
instruction
0
95,805
13
191,610
Tags: constructive algorithms, trees Correct Solution: ``` h = int(input()) A = list(map(int,input().split())) f = False for i,a in enumerate(A): if f and a != 1: f = None break else: f = a != 1 if f is not None: print('perfect') else: T = [] for j,a in enumerate(A): if j == i: x = len(T) T += [len(T)]*a print('ambiguous') print(' '.join(map(str,T))) T[x+1] = x-1 print(' '.join(map(str,T))) ```
output
1
95,805
13
191,611
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Sasha is taking part in a programming competition. In one of the problems she should check if some rooted trees are isomorphic or not. She has never seen this problem before, but, being an experienced participant, she guessed that she should match trees to some sequences and then compare these sequences instead of trees. Sasha wants to match each tree with a sequence a0, a1, ..., ah, where h is the height of the tree, and ai equals to the number of vertices that are at distance of i edges from root. Unfortunately, this time Sasha's intuition was wrong, and there could be several trees matching the same sequence. To show it, you need to write a program that, given the sequence ai, builds two non-isomorphic rooted trees that match that sequence, or determines that there is only one such tree. Two rooted trees are isomorphic, if you can reenumerate the vertices of the first one in such a way, that the index of the root becomes equal the index of the root of the second tree, and these two trees become equal. The height of a rooted tree is the maximum number of edges on a path from the root to any other vertex. Input The first line contains a single integer h (2 ≀ h ≀ 105) β€” the height of the tree. The second line contains h + 1 integers β€” the sequence a0, a1, ..., ah (1 ≀ ai ≀ 2Β·105). The sum of all ai does not exceed 2Β·105. It is guaranteed that there is at least one tree matching this sequence. Output If there is only one tree matching this sequence, print "perfect". Otherwise print "ambiguous" in the first line. In the second and in the third line print descriptions of two trees in the following format: in one line print <image> integers, the k-th of them should be the parent of vertex k or be equal to zero, if the k-th vertex is the root. These treese should be non-isomorphic and should match the given sequence. Examples Input 2 1 1 1 Output perfect Input 2 1 2 2 Output ambiguous 0 1 1 3 3 0 1 1 3 2 Note The only tree in the first example and the two printed trees from the second example are shown on the picture: <image> Submitted Solution: ``` n = int(input()) a = list(map(int, input().split())) for i in range(2, n + 1): if a[i] != 1 and a[i - 1] != 1: print('ambiguous') break else: print('perfect') exit() s1 = '' s2 = '' cnt = 0 for i in range(n + 1): s1 += a[i] * (str(cnt) + ' ') if i > 1 and a[i] != 1 and a[i - 1] != 1: s2 += str(cnt - 1) + ' ' s2 += (a[i] - 1) * (str(cnt) + ' ') else: s2 += a[i] * (str(cnt) + ' ') cnt += a[i] print(s1) print(s2) ```
instruction
0
95,806
13
191,612
Yes
output
1
95,806
13
191,613
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Sasha is taking part in a programming competition. In one of the problems she should check if some rooted trees are isomorphic or not. She has never seen this problem before, but, being an experienced participant, she guessed that she should match trees to some sequences and then compare these sequences instead of trees. Sasha wants to match each tree with a sequence a0, a1, ..., ah, where h is the height of the tree, and ai equals to the number of vertices that are at distance of i edges from root. Unfortunately, this time Sasha's intuition was wrong, and there could be several trees matching the same sequence. To show it, you need to write a program that, given the sequence ai, builds two non-isomorphic rooted trees that match that sequence, or determines that there is only one such tree. Two rooted trees are isomorphic, if you can reenumerate the vertices of the first one in such a way, that the index of the root becomes equal the index of the root of the second tree, and these two trees become equal. The height of a rooted tree is the maximum number of edges on a path from the root to any other vertex. Input The first line contains a single integer h (2 ≀ h ≀ 105) β€” the height of the tree. The second line contains h + 1 integers β€” the sequence a0, a1, ..., ah (1 ≀ ai ≀ 2Β·105). The sum of all ai does not exceed 2Β·105. It is guaranteed that there is at least one tree matching this sequence. Output If there is only one tree matching this sequence, print "perfect". Otherwise print "ambiguous" in the first line. In the second and in the third line print descriptions of two trees in the following format: in one line print <image> integers, the k-th of them should be the parent of vertex k or be equal to zero, if the k-th vertex is the root. These treese should be non-isomorphic and should match the given sequence. Examples Input 2 1 1 1 Output perfect Input 2 1 2 2 Output ambiguous 0 1 1 3 3 0 1 1 3 2 Note The only tree in the first example and the two printed trees from the second example are shown on the picture: <image> Submitted Solution: ``` n = int(input()) n+=1 l = list(map(int,input().split())) ans = 0 for i in range(n-1): if(l[i]>1 and l[i+1]>1): ans = i+1 break else: print("perfect") exit(0) print("ambiguous") prev = 0 now = 0 for i in range(n): for j in range(l[i]): print(prev,end = " ") now+=1 prev =now print() prev = 0 now = 0 for i in range(n): for j in range(l[i]): if(ans==i): print(prev-1,end = " ") ans = -1 else: print(prev,end = " ") now+=1 prev =now ```
instruction
0
95,807
13
191,614
Yes
output
1
95,807
13
191,615
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Sasha is taking part in a programming competition. In one of the problems she should check if some rooted trees are isomorphic or not. She has never seen this problem before, but, being an experienced participant, she guessed that she should match trees to some sequences and then compare these sequences instead of trees. Sasha wants to match each tree with a sequence a0, a1, ..., ah, where h is the height of the tree, and ai equals to the number of vertices that are at distance of i edges from root. Unfortunately, this time Sasha's intuition was wrong, and there could be several trees matching the same sequence. To show it, you need to write a program that, given the sequence ai, builds two non-isomorphic rooted trees that match that sequence, or determines that there is only one such tree. Two rooted trees are isomorphic, if you can reenumerate the vertices of the first one in such a way, that the index of the root becomes equal the index of the root of the second tree, and these two trees become equal. The height of a rooted tree is the maximum number of edges on a path from the root to any other vertex. Input The first line contains a single integer h (2 ≀ h ≀ 105) β€” the height of the tree. The second line contains h + 1 integers β€” the sequence a0, a1, ..., ah (1 ≀ ai ≀ 2Β·105). The sum of all ai does not exceed 2Β·105. It is guaranteed that there is at least one tree matching this sequence. Output If there is only one tree matching this sequence, print "perfect". Otherwise print "ambiguous" in the first line. In the second and in the third line print descriptions of two trees in the following format: in one line print <image> integers, the k-th of them should be the parent of vertex k or be equal to zero, if the k-th vertex is the root. These treese should be non-isomorphic and should match the given sequence. Examples Input 2 1 1 1 Output perfect Input 2 1 2 2 Output ambiguous 0 1 1 3 3 0 1 1 3 2 Note The only tree in the first example and the two printed trees from the second example are shown on the picture: <image> Submitted Solution: ``` h = int(input()) a = list(map(int,input().split())) ok = True for i in range(h): if a[i]>=2 and a[i+1]>=2: ok = False idx = i+1 if ok: print('perfect') else: print('ambiguous') ans = [] p = 0 for x in a: ans.extend([p]*x) p = len(ans) print(' '.join(map(str,ans))) ans[sum(a[:idx])] -= 1 print(' '.join(map(str,ans))) ```
instruction
0
95,808
13
191,616
Yes
output
1
95,808
13
191,617
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Sasha is taking part in a programming competition. In one of the problems she should check if some rooted trees are isomorphic or not. She has never seen this problem before, but, being an experienced participant, she guessed that she should match trees to some sequences and then compare these sequences instead of trees. Sasha wants to match each tree with a sequence a0, a1, ..., ah, where h is the height of the tree, and ai equals to the number of vertices that are at distance of i edges from root. Unfortunately, this time Sasha's intuition was wrong, and there could be several trees matching the same sequence. To show it, you need to write a program that, given the sequence ai, builds two non-isomorphic rooted trees that match that sequence, or determines that there is only one such tree. Two rooted trees are isomorphic, if you can reenumerate the vertices of the first one in such a way, that the index of the root becomes equal the index of the root of the second tree, and these two trees become equal. The height of a rooted tree is the maximum number of edges on a path from the root to any other vertex. Input The first line contains a single integer h (2 ≀ h ≀ 105) β€” the height of the tree. The second line contains h + 1 integers β€” the sequence a0, a1, ..., ah (1 ≀ ai ≀ 2Β·105). The sum of all ai does not exceed 2Β·105. It is guaranteed that there is at least one tree matching this sequence. Output If there is only one tree matching this sequence, print "perfect". Otherwise print "ambiguous" in the first line. In the second and in the third line print descriptions of two trees in the following format: in one line print <image> integers, the k-th of them should be the parent of vertex k or be equal to zero, if the k-th vertex is the root. These treese should be non-isomorphic and should match the given sequence. Examples Input 2 1 1 1 Output perfect Input 2 1 2 2 Output ambiguous 0 1 1 3 3 0 1 1 3 2 Note The only tree in the first example and the two printed trees from the second example are shown on the picture: <image> Submitted Solution: ``` n = int(input()) *a, = map(int, input().split()) b, c = [0], [0] cur = 1 for i in range(1, n + 1): for j in range(a[i]): b.append(cur) cur += a[i] cur = 1 for i in range(1, n + 1): if a[i] > 1 and a[i - 1] > 1: c.append(cur - 1) for j in range(1, a[i]): c.append(cur) else: for j in range(a[i]): c.append(cur) cur += a[i] if b == c: exit(print('perfect')) print('ambiguous') print(*b) print(*c) ```
instruction
0
95,809
13
191,618
Yes
output
1
95,809
13
191,619
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Sasha is taking part in a programming competition. In one of the problems she should check if some rooted trees are isomorphic or not. She has never seen this problem before, but, being an experienced participant, she guessed that she should match trees to some sequences and then compare these sequences instead of trees. Sasha wants to match each tree with a sequence a0, a1, ..., ah, where h is the height of the tree, and ai equals to the number of vertices that are at distance of i edges from root. Unfortunately, this time Sasha's intuition was wrong, and there could be several trees matching the same sequence. To show it, you need to write a program that, given the sequence ai, builds two non-isomorphic rooted trees that match that sequence, or determines that there is only one such tree. Two rooted trees are isomorphic, if you can reenumerate the vertices of the first one in such a way, that the index of the root becomes equal the index of the root of the second tree, and these two trees become equal. The height of a rooted tree is the maximum number of edges on a path from the root to any other vertex. Input The first line contains a single integer h (2 ≀ h ≀ 105) β€” the height of the tree. The second line contains h + 1 integers β€” the sequence a0, a1, ..., ah (1 ≀ ai ≀ 2Β·105). The sum of all ai does not exceed 2Β·105. It is guaranteed that there is at least one tree matching this sequence. Output If there is only one tree matching this sequence, print "perfect". Otherwise print "ambiguous" in the first line. In the second and in the third line print descriptions of two trees in the following format: in one line print <image> integers, the k-th of them should be the parent of vertex k or be equal to zero, if the k-th vertex is the root. These treese should be non-isomorphic and should match the given sequence. Examples Input 2 1 1 1 Output perfect Input 2 1 2 2 Output ambiguous 0 1 1 3 3 0 1 1 3 2 Note The only tree in the first example and the two printed trees from the second example are shown on the picture: <image> Submitted Solution: ``` n = int(input()) arr = list(map(int,input().split())) flag = 0 for i in range(1,n+1): if arr[i]>1 and arr[i-1]>1: flag = 1 break if not flag: print("perfect") exit(0) print("ambiguous") st = 0 prr = [] for i in range(n+1): prr = prr+[st]*arr[i] st+=arr[i] print(*prr) st = 0 prr = [] for i in range(n+1): if flag and i and arr[i]>1 and arr[i-1]>1: flag = False prr+=[st-1]*arr[i] else: prr+=[st]*arr[i] st+=arr[i] print(*prr) ```
instruction
0
95,810
13
191,620
No
output
1
95,810
13
191,621
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Sasha is taking part in a programming competition. In one of the problems she should check if some rooted trees are isomorphic or not. She has never seen this problem before, but, being an experienced participant, she guessed that she should match trees to some sequences and then compare these sequences instead of trees. Sasha wants to match each tree with a sequence a0, a1, ..., ah, where h is the height of the tree, and ai equals to the number of vertices that are at distance of i edges from root. Unfortunately, this time Sasha's intuition was wrong, and there could be several trees matching the same sequence. To show it, you need to write a program that, given the sequence ai, builds two non-isomorphic rooted trees that match that sequence, or determines that there is only one such tree. Two rooted trees are isomorphic, if you can reenumerate the vertices of the first one in such a way, that the index of the root becomes equal the index of the root of the second tree, and these two trees become equal. The height of a rooted tree is the maximum number of edges on a path from the root to any other vertex. Input The first line contains a single integer h (2 ≀ h ≀ 105) β€” the height of the tree. The second line contains h + 1 integers β€” the sequence a0, a1, ..., ah (1 ≀ ai ≀ 2Β·105). The sum of all ai does not exceed 2Β·105. It is guaranteed that there is at least one tree matching this sequence. Output If there is only one tree matching this sequence, print "perfect". Otherwise print "ambiguous" in the first line. In the second and in the third line print descriptions of two trees in the following format: in one line print <image> integers, the k-th of them should be the parent of vertex k or be equal to zero, if the k-th vertex is the root. These treese should be non-isomorphic and should match the given sequence. Examples Input 2 1 1 1 Output perfect Input 2 1 2 2 Output ambiguous 0 1 1 3 3 0 1 1 3 2 Note The only tree in the first example and the two printed trees from the second example are shown on the picture: <image> Submitted Solution: ``` h = int(input()) a = list(map(int, input().split())) perfect = True for i in range(len(a) - 1): if (a[i] != 1): perfect = False print ("perfect" if perfect else "ambiguous") ret1 = [0] * sum(a) ret2 = [0] * sum(a) #print (ret1) node = 0; divided = False p1=0 p2=0 if (perfect == False): for i in range(len(a)): for j in range(a[i]): ret1[node] = p1 ret2[node] = p2; node += 1; p1 = p2 = node; if (a[i] != 1 and divided == False): divided = True; p1 = node; p2 = node - 1; print (' '.join(str(x) for x in ret1)) print (' '.join(str(x) for x in ret2)) ```
instruction
0
95,811
13
191,622
No
output
1
95,811
13
191,623
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Sasha is taking part in a programming competition. In one of the problems she should check if some rooted trees are isomorphic or not. She has never seen this problem before, but, being an experienced participant, she guessed that she should match trees to some sequences and then compare these sequences instead of trees. Sasha wants to match each tree with a sequence a0, a1, ..., ah, where h is the height of the tree, and ai equals to the number of vertices that are at distance of i edges from root. Unfortunately, this time Sasha's intuition was wrong, and there could be several trees matching the same sequence. To show it, you need to write a program that, given the sequence ai, builds two non-isomorphic rooted trees that match that sequence, or determines that there is only one such tree. Two rooted trees are isomorphic, if you can reenumerate the vertices of the first one in such a way, that the index of the root becomes equal the index of the root of the second tree, and these two trees become equal. The height of a rooted tree is the maximum number of edges on a path from the root to any other vertex. Input The first line contains a single integer h (2 ≀ h ≀ 105) β€” the height of the tree. The second line contains h + 1 integers β€” the sequence a0, a1, ..., ah (1 ≀ ai ≀ 2Β·105). The sum of all ai does not exceed 2Β·105. It is guaranteed that there is at least one tree matching this sequence. Output If there is only one tree matching this sequence, print "perfect". Otherwise print "ambiguous" in the first line. In the second and in the third line print descriptions of two trees in the following format: in one line print <image> integers, the k-th of them should be the parent of vertex k or be equal to zero, if the k-th vertex is the root. These treese should be non-isomorphic and should match the given sequence. Examples Input 2 1 1 1 Output perfect Input 2 1 2 2 Output ambiguous 0 1 1 3 3 0 1 1 3 2 Note The only tree in the first example and the two printed trees from the second example are shown on the picture: <image> Submitted Solution: ``` n = int(input()) c = list(map(int, input().split())) f = True for i in range(n + 1): if i % 2 == 0 and c[i] != 1: f = False if f: print('perfect') else: last = 0 print('ambiguous') g = 0 for i in range(n + 1): for j in range(c[i]): print(g, end=' ') g += c[i] if i > 0: if c[i] > 1 and c[i - 1]: last = i print() g = 0 for i in range(n + 1): if i != last: for j in range(c[i]): print(g, end=' ') else: for j in range(c[i] - 1): print(g, end=' ') print(g - 1, end=' ') g += c[i] ```
instruction
0
95,812
13
191,624
No
output
1
95,812
13
191,625
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Sasha is taking part in a programming competition. In one of the problems she should check if some rooted trees are isomorphic or not. She has never seen this problem before, but, being an experienced participant, she guessed that she should match trees to some sequences and then compare these sequences instead of trees. Sasha wants to match each tree with a sequence a0, a1, ..., ah, where h is the height of the tree, and ai equals to the number of vertices that are at distance of i edges from root. Unfortunately, this time Sasha's intuition was wrong, and there could be several trees matching the same sequence. To show it, you need to write a program that, given the sequence ai, builds two non-isomorphic rooted trees that match that sequence, or determines that there is only one such tree. Two rooted trees are isomorphic, if you can reenumerate the vertices of the first one in such a way, that the index of the root becomes equal the index of the root of the second tree, and these two trees become equal. The height of a rooted tree is the maximum number of edges on a path from the root to any other vertex. Input The first line contains a single integer h (2 ≀ h ≀ 105) β€” the height of the tree. The second line contains h + 1 integers β€” the sequence a0, a1, ..., ah (1 ≀ ai ≀ 2Β·105). The sum of all ai does not exceed 2Β·105. It is guaranteed that there is at least one tree matching this sequence. Output If there is only one tree matching this sequence, print "perfect". Otherwise print "ambiguous" in the first line. In the second and in the third line print descriptions of two trees in the following format: in one line print <image> integers, the k-th of them should be the parent of vertex k or be equal to zero, if the k-th vertex is the root. These treese should be non-isomorphic and should match the given sequence. Examples Input 2 1 1 1 Output perfect Input 2 1 2 2 Output ambiguous 0 1 1 3 3 0 1 1 3 2 Note The only tree in the first example and the two printed trees from the second example are shown on the picture: <image> Submitted Solution: ``` def get_num_divisions(nodes, subnodes): divisions = [] if nodes - 1: for x in range(subnodes + 1): for y in get_num_divisions(nodes-1, subnodes-x): divisions.append([x]+y) else: divisions.append([subnodes]) for div in divisions: div.sort() import itertools divisions.sort() return list(k for k, _ in itertools.groupby(divisions)) def get_trees_structs(levels): trees = [] for x in range(len(levels)-1): trees.append(get_num_divisions(levels[x], levels[x+1])) return trees def get_trees_variants(structure): variants = [] if structure: for var in structure[0]: others = get_trees_variants(structure[1:]) if others: for other in others: variants.append(var + other) else: variants.append(var) return variants def get_tree_represantion(variant, levels): result = "0 " i = 1 for var in variant: for x in range(var): result += "{0} ".format(i) i += 1 return result class CodeforcesTask901ASolution: def __init__(self): self.result = '' self.height = 0 self.levels = [] def read_input(self): self.height = int(input()) self.levels = [int(x) for x in input().split(" ")] def process_task(self): struct = get_trees_structs(self.levels) variants = get_trees_variants(struct) if len(variants) == 1: self.result = "perfect" else: self.result += "{0}\n".format(get_tree_represantion(variants[0], self.levels)) self.result += "{0}\n".format(get_tree_represantion(variants[1], self.levels)) def get_result(self): return self.result if __name__ == "__main__": Solution = CodeforcesTask901ASolution() Solution.read_input() Solution.process_task() print(Solution.get_result()) ```
instruction
0
95,813
13
191,626
No
output
1
95,813
13
191,627
Provide a correct Python 3 solution for this coding contest problem. Given is an integer sequence of length N+1: A_0, A_1, A_2, \ldots, A_N. Is there a binary tree of depth N such that, for each d = 0, 1, \ldots, N, there are exactly A_d leaves at depth d? If such a tree exists, print the maximum possible number of vertices in such a tree; otherwise, print -1. Constraints * 0 \leq N \leq 10^5 * 0 \leq A_i \leq 10^{8} (0 \leq i \leq N) * A_N \geq 1 * All values in input are integers. Input Input is given from Standard Input in the following format: N A_0 A_1 A_2 \cdots A_N Output Print the answer as an integer. Examples Input 3 0 1 1 2 Output 7 Input 4 0 0 1 0 2 Output 10 Input 2 0 3 1 Output -1 Input 1 1 1 Output -1 Input 10 0 0 1 1 2 3 5 8 13 21 34 Output 264
instruction
0
95,855
13
191,710
"Correct Solution: ``` n = int(input()) values = list(map(int, input().split())) from itertools import accumulate copy = values[:] copy.reverse() acc = list(accumulate(copy)) acc.reverse() b = 1 total = 1 for i in range(n+1): a = values[i] bCandidate = b - a if bCandidate < 0: print(-1) exit() b = min(2*bCandidate, acc[i] - a) total += b print(total) ```
output
1
95,855
13
191,711
Provide a correct Python 3 solution for this coding contest problem. Given is an integer sequence of length N+1: A_0, A_1, A_2, \ldots, A_N. Is there a binary tree of depth N such that, for each d = 0, 1, \ldots, N, there are exactly A_d leaves at depth d? If such a tree exists, print the maximum possible number of vertices in such a tree; otherwise, print -1. Constraints * 0 \leq N \leq 10^5 * 0 \leq A_i \leq 10^{8} (0 \leq i \leq N) * A_N \geq 1 * All values in input are integers. Input Input is given from Standard Input in the following format: N A_0 A_1 A_2 \cdots A_N Output Print the answer as an integer. Examples Input 3 0 1 1 2 Output 7 Input 4 0 0 1 0 2 Output 10 Input 2 0 3 1 Output -1 Input 1 1 1 Output -1 Input 10 0 0 1 1 2 3 5 8 13 21 34 Output 264
instruction
0
95,856
13
191,712
"Correct Solution: ``` n = int(input()) a = list(map(int,input().split())) b = [0 for i in range(n+1)] leaf = sum(a) if n == 0 and a[0] != 1: print(-1) exit() b[0] = 1 - a[0] leaf -= a[0] ans = 1 for i in range(1,n+1): kosu = min(b[i-1] * 2,leaf) ans += kosu b[i] = kosu - a[i] if b[i] < 0: print(-1) exit() leaf -= a[i] print(ans) ```
output
1
95,856
13
191,713
Provide a correct Python 3 solution for this coding contest problem. Given is an integer sequence of length N+1: A_0, A_1, A_2, \ldots, A_N. Is there a binary tree of depth N such that, for each d = 0, 1, \ldots, N, there are exactly A_d leaves at depth d? If such a tree exists, print the maximum possible number of vertices in such a tree; otherwise, print -1. Constraints * 0 \leq N \leq 10^5 * 0 \leq A_i \leq 10^{8} (0 \leq i \leq N) * A_N \geq 1 * All values in input are integers. Input Input is given from Standard Input in the following format: N A_0 A_1 A_2 \cdots A_N Output Print the answer as an integer. Examples Input 3 0 1 1 2 Output 7 Input 4 0 0 1 0 2 Output 10 Input 2 0 3 1 Output -1 Input 1 1 1 Output -1 Input 10 0 0 1 1 2 3 5 8 13 21 34 Output 264
instruction
0
95,857
13
191,714
"Correct Solution: ``` n=int(input()) a=list(map(int,input().split())) if n==0: if a[0]==1:print(1) else:print(-1) exit() if a[0]: exit(print(-1)) b=[1] for i in range(1,n+1): b.append(b[-1]*2-a[i]) b[-1]=a[-1] for i in range(n,0,-1): b[i-1]=min(b[i-1],b[i]) if not(b[i-1]<=b[i]<=2*b[i-1]):exit(print(-1)) b[i-1]+=a[i-1] print(sum(b)) ```
output
1
95,857
13
191,715
Provide a correct Python 3 solution for this coding contest problem. Given is an integer sequence of length N+1: A_0, A_1, A_2, \ldots, A_N. Is there a binary tree of depth N such that, for each d = 0, 1, \ldots, N, there are exactly A_d leaves at depth d? If such a tree exists, print the maximum possible number of vertices in such a tree; otherwise, print -1. Constraints * 0 \leq N \leq 10^5 * 0 \leq A_i \leq 10^{8} (0 \leq i \leq N) * A_N \geq 1 * All values in input are integers. Input Input is given from Standard Input in the following format: N A_0 A_1 A_2 \cdots A_N Output Print the answer as an integer. Examples Input 3 0 1 1 2 Output 7 Input 4 0 0 1 0 2 Output 10 Input 2 0 3 1 Output -1 Input 1 1 1 Output -1 Input 10 0 0 1 1 2 3 5 8 13 21 34 Output 264
instruction
0
95,858
13
191,716
"Correct Solution: ``` import sys input = sys.stdin.readline N = int(input()) A = list(map(int, input().split())) leaf = sum(A) ans = 0 node = 1 for i in range(N+1): if A[i] > node or leaf == 0: ans = -1 break ans += node leaf -= A[i] node = min(2*(node-A[i]), leaf) print(ans) ```
output
1
95,858
13
191,717
Provide a correct Python 3 solution for this coding contest problem. Given is an integer sequence of length N+1: A_0, A_1, A_2, \ldots, A_N. Is there a binary tree of depth N such that, for each d = 0, 1, \ldots, N, there are exactly A_d leaves at depth d? If such a tree exists, print the maximum possible number of vertices in such a tree; otherwise, print -1. Constraints * 0 \leq N \leq 10^5 * 0 \leq A_i \leq 10^{8} (0 \leq i \leq N) * A_N \geq 1 * All values in input are integers. Input Input is given from Standard Input in the following format: N A_0 A_1 A_2 \cdots A_N Output Print the answer as an integer. Examples Input 3 0 1 1 2 Output 7 Input 4 0 0 1 0 2 Output 10 Input 2 0 3 1 Output -1 Input 1 1 1 Output -1 Input 10 0 0 1 1 2 3 5 8 13 21 34 Output 264
instruction
0
95,859
13
191,718
"Correct Solution: ``` N = int(input()) *A, = map(int, input().split()) Asum = [a for a in A] for i in range(N-1, -1, -1): Asum[i] += Asum[i+1] ans = 0 v = 1 # 子にγͺγ‚Œγ‚‹ι ‚η‚Ήζ•° for i in range(N+1): if v < A[i]: ans = -1 break ans += v p = v-A[i] if i < N: v = min(Asum[i+1], 2*p) print(ans) ```
output
1
95,859
13
191,719