message
stringlengths
2
49.9k
message_type
stringclasses
2 values
message_id
int64
0
1
conversation_id
int64
446
108k
cluster
float64
13
13
__index_level_0__
int64
892
217k
Provide tags and a correct Python 3 solution for this coding contest problem. You are given n integer numbers a_1, a_2, ..., a_n. Consider graph on n nodes, in which nodes i, j (i≠ j) are connected if and only if, a_i AND a_j≠ 0, where AND denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND). Find the length of the shortest cycle in this graph or determine that it doesn't have cycles at all. Input The first line contains one integer n (1 ≤ n ≤ 10^5) — number of numbers. The second line contains n integer numbers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^{18}). Output If the graph doesn't have any cycles, output -1. Else output the length of the shortest cycle. Examples Input 4 3 6 28 9 Output 4 Input 5 5 12 9 16 48 Output 3 Input 4 1 2 4 8 Output -1 Note In the first example, the shortest cycle is (9, 3, 6, 28). In the second example, the shortest cycle is (5, 12, 9). The graph has no cycles in the third example.
instruction
0
101,287
13
202,574
Tags: bitmasks, brute force, graphs, shortest paths Correct Solution: ``` import math edges = [] result = -1 def dfs(ns, path, visited, last, now): visited[now] = True global edges for i in edges[now]: if i == last: continue if i in path: new_result = len(path) - path.index(i) global result if result < 0 or result > new_result: result = new_result continue dfs(ns, path + [i], visited, now, i) def solve(): n = int(input()) ns = [int(x) for x in input().split()] global edges edges = [] for i in range(n): edges.append(list()) p = 1 for i in range(70): s = [] for t in range(n): if ns[t] & p != 0: s.append(t) if len(s) >= 3: return 3 if len(s) == 2: edges[s[0]].append(s[1]) edges[s[1]].append(s[0]) p <<= 1 # print(edges) global result result = -1 visited = [False] * n for start in range(n): if not visited[start]: dfs(ns, [start], visited, -1, start) return result def main(): print(solve()) if __name__ == '__main__': main() ```
output
1
101,287
13
202,575
Provide tags and a correct Python 3 solution for this coding contest problem. You are given n integer numbers a_1, a_2, ..., a_n. Consider graph on n nodes, in which nodes i, j (i≠ j) are connected if and only if, a_i AND a_j≠ 0, where AND denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND). Find the length of the shortest cycle in this graph or determine that it doesn't have cycles at all. Input The first line contains one integer n (1 ≤ n ≤ 10^5) — number of numbers. The second line contains n integer numbers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^{18}). Output If the graph doesn't have any cycles, output -1. Else output the length of the shortest cycle. Examples Input 4 3 6 28 9 Output 4 Input 5 5 12 9 16 48 Output 3 Input 4 1 2 4 8 Output -1 Note In the first example, the shortest cycle is (9, 3, 6, 28). In the second example, the shortest cycle is (5, 12, 9). The graph has no cycles in the third example.
instruction
0
101,288
13
202,576
Tags: bitmasks, brute force, graphs, shortest paths Correct Solution: ``` # Using BFS from collections import defaultdict import queue class Graph: def __init__(self, length): self.length = length self.graph = defaultdict(list) def addEdge(self,u,v): self.graph[u].append(v) def bfs(self, s, max_len): D = [self.length + 1] * self.length visited = [False] * self.length P = [None] * self.length stack = queue.Queue() stack.put(s) visited[s] = True D[s] = 0 while not stack.empty(): v = stack.get() # print(v, end = " ") if D[v] >= max_len: break for w in self.graph[v]: if visited[w] == False: visited[w] = True stack.put(w) D[w] = D[v] + 1 P[w] = v elif P[v] != w: # P[w] = v # print(w) # print(P) # return True, find_cycle_length(w, P) return True, D[v] + D[w] + 1 # print("") return False, self.length + 1 n = int(input()) nums = list(map(int, input().split(' '))) a = [] for i in range(n): if nums[i] != 0: a.append(nums[i]) n = len(a) if n < 3: print(-1) elif n > 120: print(3) else: G = Graph(n) for i in range(n-1): for j in range(i+1, n): if a[i] & a[j] != 0: G.addEdge(i, j) G.addEdge(j, i) # print(G.graph) min_len = n + 1 for i in range(n): has_cycle, length = G.bfs(i, min_len) if has_cycle and length < min_len: min_len = length if min_len == (n + 1): print(-1) else: print(min_len) ```
output
1
101,288
13
202,577
Provide tags and a correct Python 3 solution for this coding contest problem. You are given n integer numbers a_1, a_2, ..., a_n. Consider graph on n nodes, in which nodes i, j (i≠ j) are connected if and only if, a_i AND a_j≠ 0, where AND denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND). Find the length of the shortest cycle in this graph or determine that it doesn't have cycles at all. Input The first line contains one integer n (1 ≤ n ≤ 10^5) — number of numbers. The second line contains n integer numbers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^{18}). Output If the graph doesn't have any cycles, output -1. Else output the length of the shortest cycle. Examples Input 4 3 6 28 9 Output 4 Input 5 5 12 9 16 48 Output 3 Input 4 1 2 4 8 Output -1 Note In the first example, the shortest cycle is (9, 3, 6, 28). In the second example, the shortest cycle is (5, 12, 9). The graph has no cycles in the third example.
instruction
0
101,289
13
202,578
Tags: bitmasks, brute force, graphs, shortest paths Correct Solution: ``` import sys input = sys.stdin.readline N = int(input()) A = list(map(int, input().split())) L = max(A).bit_length() ans = -1 graph = [[] for _ in range(N)] V = [] for l in range(L): P = [] for i in range(N): if (1 << l) & A[i]: P.append(i) if len(P) > 2: ans = 3 break elif len(P) == 2: p0, p1 = P graph[p0].append(p1) graph[p1].append(p0) V.append(P) def bfs(s, g): a = -1 q = [s] checked = [False]*N checked[s] = True d = 0 while q: qq = [] d += 1 for p in q: for np in graph[p]: if np == g: if d == 1: continue else: return d if not checked[np]: qq.append(np) checked[np] = True q = qq return -1 if ans == 3: print(3) else: ans = 10**9 for s, g in V: cycle = bfs(s, g) if cycle == -1: continue ans = min(cycle+1, ans) if ans == 10**9: print(-1) else: print(ans) ```
output
1
101,289
13
202,579
Provide tags and a correct Python 3 solution for this coding contest problem. You are given n integer numbers a_1, a_2, ..., a_n. Consider graph on n nodes, in which nodes i, j (i≠ j) are connected if and only if, a_i AND a_j≠ 0, where AND denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND). Find the length of the shortest cycle in this graph or determine that it doesn't have cycles at all. Input The first line contains one integer n (1 ≤ n ≤ 10^5) — number of numbers. The second line contains n integer numbers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^{18}). Output If the graph doesn't have any cycles, output -1. Else output the length of the shortest cycle. Examples Input 4 3 6 28 9 Output 4 Input 5 5 12 9 16 48 Output 3 Input 4 1 2 4 8 Output -1 Note In the first example, the shortest cycle is (9, 3, 6, 28). In the second example, the shortest cycle is (5, 12, 9). The graph has no cycles in the third example.
instruction
0
101,290
13
202,580
Tags: bitmasks, brute force, graphs, shortest paths Correct Solution: ``` from collections import * import sys # "". join(strings) def ri(): return int(input()) def rl(): return list(map(int, input().split())) n = ri() aa = rl() zero_cnt = 0 aa = [value for value in aa if value != 0] n = len(aa) edges = set() graph = defaultdict(list) bit_shared = defaultdict(list) #2^60 > 10^18 >= aa[i]. So we have 60 bits to check, between 0 and 59. #Also note that for a given bit, if 3 numbers share it, then the answer is 3 for k in range(60): for i in range(n): if (1 << k) & aa[i]: bit_shared[k].append(i) if len(bit_shared[k]) >= 3: print(3) sys.exit() # print("bit: ", bit_shared) #we build the graph for i in range(n): for j in range(i + 1, n): if aa[i] & aa[j]: if (i,j) not in edges: graph[i].append(j) graph[j].append(i) edges.add((i,j)) # we need a set, because sometimes many edges between same 2 vertices, but they dont count as cycle according to: #ANNOUCEMENT : Note that the graph does not contain parallel edges. Therefore, one edge can not be a cycle. A cycle should contain at least three distinct vertices. # print("graph: ",graph) # print("edges: ",edges) #if we havent exited yet, it means for all bit 2^k, it is shared at most between two elements of aa. #We have to find the shortest length cycle of this graph. #I think we can chose to iterate over edges (there are less than 60 of them) #Or we can iterate over vertices (there are less of 60*3 + 1 = 183 of them because of pigeonhole principle) #let's iterate of vertices v and use BFS to find the shortest cycle containing v ans = 10**5 # For all vertices for i in range(n): # Make distance maximum dist = [int(1e5)] * n # Take a imaginary parent par = [-1] * n # Distance of source to source is 0 dist[i] = 0 q = deque() # Push the source element q.append(i) # Continue until queue is not empty while q: # Take the first element x = q[0] q.popleft() # Traverse for all it's childs for child in graph[x]: # If it is not visited yet if dist[child] == int(1e5): # Increase distance by 1 dist[child] = 1 + dist[x] # Change parent par[child] = x # Push into the queue q.append(child) # If it is already visited elif par[x] != child and par[child] != x: ans = min(ans, dist[x] + dist[child] + 1) if ans == 10**5: print(-1) else: print(ans) ```
output
1
101,290
13
202,581
Provide tags and a correct Python 3 solution for this coding contest problem. You are given n integer numbers a_1, a_2, ..., a_n. Consider graph on n nodes, in which nodes i, j (i≠ j) are connected if and only if, a_i AND a_j≠ 0, where AND denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND). Find the length of the shortest cycle in this graph or determine that it doesn't have cycles at all. Input The first line contains one integer n (1 ≤ n ≤ 10^5) — number of numbers. The second line contains n integer numbers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^{18}). Output If the graph doesn't have any cycles, output -1. Else output the length of the shortest cycle. Examples Input 4 3 6 28 9 Output 4 Input 5 5 12 9 16 48 Output 3 Input 4 1 2 4 8 Output -1 Note In the first example, the shortest cycle is (9, 3, 6, 28). In the second example, the shortest cycle is (5, 12, 9). The graph has no cycles in the third example.
instruction
0
101,291
13
202,582
Tags: bitmasks, brute force, graphs, shortest paths Correct Solution: ``` def bfs(g, src, dest): visited = {} dist = {} for i in g: visited[i] = False dist[i] = 1e18 dist[src] = 0 visited[src] = True q = [] q.append(src) while q: src = q.pop(0) for i in g[src]: if visited[i] == False: visited[i] = True dist[i] = min(dist[i], dist[src] + 1) q.append(i) return dist[dest] #print(timeit.timeit("c += 1", "c = 0", number = 100000000) #from random import * #[randint(1, int(1e18)) for i in range(100000)] n = int(input()) a = list(map(int, input().split())) c = 0 #this overlooks parallel edges a = sorted(a) while n != 0 and a[0] == 0: a.pop(0) n -= 1 for i in range(64): c = 0 for j in range(n): if ((a[j] >> i) & 1): c += 1 if c == 3: break if c == 3: break if c == 3:#[565299879350784, 4508014854799360, 0, 0, 0, 4503635094929409, 18014810826352646, 306526525186934784, 0, 0]: print(3) else: g = {} #create adjacency list for i in range(64): buff = [-1, -1] for j in range(n): if (a[j] >> i) & 1: if buff[0] == -1: buff[0] = j elif buff[1] == -1: buff[1] = j if buff[0] not in g: g[buff[0]] = [] g[buff[0]].append(buff[1]) if buff[1] not in g: g[buff[1]] = [] g[buff[1]].append(buff[0]) #this completes our graph tg = {} dist = [] for i in g: for j in g[i]: tg = g tg[i].remove(j) tg[j].remove(i) dist.append( bfs(tg, i, j) ) while len(dist) != 0 and min(dist) < 2: dist.remove(min(dist)) if len(dist) != 0 and min(dist) < 1e18: print(min(dist) + 1) else: print(-1) ```
output
1
101,291
13
202,583
Provide tags and a correct Python 3 solution for this coding contest problem. You are given n integer numbers a_1, a_2, ..., a_n. Consider graph on n nodes, in which nodes i, j (i≠ j) are connected if and only if, a_i AND a_j≠ 0, where AND denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND). Find the length of the shortest cycle in this graph or determine that it doesn't have cycles at all. Input The first line contains one integer n (1 ≤ n ≤ 10^5) — number of numbers. The second line contains n integer numbers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^{18}). Output If the graph doesn't have any cycles, output -1. Else output the length of the shortest cycle. Examples Input 4 3 6 28 9 Output 4 Input 5 5 12 9 16 48 Output 3 Input 4 1 2 4 8 Output -1 Note In the first example, the shortest cycle is (9, 3, 6, 28). In the second example, the shortest cycle is (5, 12, 9). The graph has no cycles in the third example.
instruction
0
101,292
13
202,584
Tags: bitmasks, brute force, graphs, shortest paths 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 sys import maxsize as INT_MAX from collections import defaultdict,deque def shortest_cycle(n: int) -> int: ans = INT_MAX for i in range(n): dist=defaultdict(lambda: -1);par=defaultdict(lambda: -1);dist[i]=0 q = deque([]) ;q.append(i) while q: x=q[0];q.popleft() for child in graph[x]: if dist[child] == -1: dist[child]=1+dist[x];par[child]=x;q.append(child) elif par[x]!= child and par[child]!= x: ans=min(ans,dist[x]+dist[child] + 1) if ans==INT_MAX: return -1 else: return ans n=int(input());vals=list(map(int,input().split()));zer=0 for s in range(n): if vals[s]==0: zer+=1 if n-zer>=121: print(3) else: bit=[[] for s in range(60)];info=defaultdict(list) for s in range(n): num=vals[s] for i in range(59,-1,-1): if num-2**i>=0: bit[i].append(s);num-=2**i;info[vals[s]].append(i) graph=[[] for s in range(n)];tracker=[set([]) for s in range(n)] for s in range(n): for i in info[vals[s]]: for b in range(len(bit[i])): if bit[i][b]!=s and not(bit[i][b] in tracker[s]): graph[s].append(bit[i][b]);tracker[s].add(bit[i][b]) print(shortest_cycle(n)) ```
output
1
101,292
13
202,585
Provide tags and a correct Python 3 solution for this coding contest problem. You are given n integer numbers a_1, a_2, ..., a_n. Consider graph on n nodes, in which nodes i, j (i≠ j) are connected if and only if, a_i AND a_j≠ 0, where AND denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND). Find the length of the shortest cycle in this graph or determine that it doesn't have cycles at all. Input The first line contains one integer n (1 ≤ n ≤ 10^5) — number of numbers. The second line contains n integer numbers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^{18}). Output If the graph doesn't have any cycles, output -1. Else output the length of the shortest cycle. Examples Input 4 3 6 28 9 Output 4 Input 5 5 12 9 16 48 Output 3 Input 4 1 2 4 8 Output -1 Note In the first example, the shortest cycle is (9, 3, 6, 28). In the second example, the shortest cycle is (5, 12, 9). The graph has no cycles in the third example.
instruction
0
101,293
13
202,586
Tags: bitmasks, brute force, graphs, shortest paths Correct Solution: ``` from collections import * import sys def ri(): return int(input()) def rl(): return list(map(int, input().split())) n = ri() aa = rl() zero_cnt = 0 aa = [value for value in aa if value != 0] n = len(aa) edges = set() graph = defaultdict(list) bit_shared = defaultdict(list) #2^60 > 10^18 >= aa[i]. So we have 60 bits to check, between 0 and 59. #Also note that for a given bit, if 3 numbers share it, then the answer is 3 for k in range(60): for i in range(n): if (1 << k) & aa[i]: bit_shared[k].append(i) if len(bit_shared[k]) >= 3: print(3) sys.exit() # print("bit: ", bit_shared) #we build the graph for i in range(n): for j in range(i + 1, n): if aa[i] & aa[j]: if (i,j) not in edges: graph[i].append(j) graph[j].append(i) edges.add((i,j)) # we use a set, because sometimes many edges between same 2 vertices, but they dont count as cycle according to: #ANNOUCEMENT : Note that the graph does not contain parallel edges. Therefore, one edge can not be a cycle. A cycle should contain at least three distinct vertices. # print("graph: ",graph) # print("edges: ",edges) #if we havent exited yet, it means for all bit 2^k, it is shared at most between two elements of aa. #We have to find the shortest length cycle of this graph. #I think we can chose to iterate over edges (there are less than 60 of them) #Or we can iterate over vertices (there are less of 60*3 + 1 = 183 of them because of pigeonhole principle) #let's iterate of vertices v and use Dijikstra to find the shortest cycle containing v ########################################################################################################### ####Approach: For every vertex, we check if it is possible to get the shortest cycle involving this vertex. #### For every vertex first, push current vertex into the queue and then it’s neighbours #### and if vertex which is already visited comes again then the cycle is present. ########################################################################################################### ans = 10**5 # For all vertices for i in range(n): # dist stores the distance to i. Make distance maximum dist = [int(1e5)] * n # except distance from i to i is 0 dist[i] = 0 # Take a imaginary parent par = [-1] * n #make a queue with just the source element q = deque([i]) # Continue until queue is not empty while q: # Take the first element x = q.popleft() # Traverse for all it's children for child in graph[x]: # If it is not visited yet if dist[child] == int(1e5): # Increase distance by 1 dist[child] = 1 + dist[x] # Change parent par[child] = x # Push into the queue q.append(child) # If it is already visited elif par[x] != child and par[child] != x: ans = min(ans, dist[x] + dist[child] + 1) if ans == 10**5: print(-1) else: print(ans) ```
output
1
101,293
13
202,587
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given n integer numbers a_1, a_2, ..., a_n. Consider graph on n nodes, in which nodes i, j (i≠ j) are connected if and only if, a_i AND a_j≠ 0, where AND denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND). Find the length of the shortest cycle in this graph or determine that it doesn't have cycles at all. Input The first line contains one integer n (1 ≤ n ≤ 10^5) — number of numbers. The second line contains n integer numbers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^{18}). Output If the graph doesn't have any cycles, output -1. Else output the length of the shortest cycle. Examples Input 4 3 6 28 9 Output 4 Input 5 5 12 9 16 48 Output 3 Input 4 1 2 4 8 Output -1 Note In the first example, the shortest cycle is (9, 3, 6, 28). In the second example, the shortest cycle is (5, 12, 9). The graph has no cycles in the third example. Submitted Solution: ``` import sys,math,itertools from collections import Counter,deque,defaultdict from bisect import bisect_left,bisect_right from heapq import heappop,heappush,heapify mod = 10**9+7 INF = float('inf') def inp(): return int(sys.stdin.readline()) def inpl(): return list(map(int, sys.stdin.readline().split())) n = inp() a = inpl() b = [] for x in a: if x != 0: b.append(x) n = len(b) if n > 120: print(3); quit() if n == 0: print(-1); quit() g = [[] for _ in range(n)] for i in range(n): for j in range(i+1,n): for k in range(65): if (b[i]>>k)%2 and (b[j]>>k)%2: g[i].append(j) g[j].append(i) break res = INF for i in range(n): dist = [INF]*n; dist[i] = 0 fro = [-1]*n q = deque(); q.append(i) while q: nv = q.popleft() for v in g[nv]: if fro[nv] == v: continue if dist[v] != INF: if fro[v] == fro[nv]: res = 3 else: res = min(res, dist[nv]+dist[v]+1) else: fro[v] = nv dist[v] = dist[nv] + 1 q.append(v) print(res if res != INF else -1) ```
instruction
0
101,294
13
202,588
Yes
output
1
101,294
13
202,589
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given n integer numbers a_1, a_2, ..., a_n. Consider graph on n nodes, in which nodes i, j (i≠ j) are connected if and only if, a_i AND a_j≠ 0, where AND denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND). Find the length of the shortest cycle in this graph or determine that it doesn't have cycles at all. Input The first line contains one integer n (1 ≤ n ≤ 10^5) — number of numbers. The second line contains n integer numbers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^{18}). Output If the graph doesn't have any cycles, output -1. Else output the length of the shortest cycle. Examples Input 4 3 6 28 9 Output 4 Input 5 5 12 9 16 48 Output 3 Input 4 1 2 4 8 Output -1 Note In the first example, the shortest cycle is (9, 3, 6, 28). In the second example, the shortest cycle is (5, 12, 9). The graph has no cycles in the third example. Submitted Solution: ``` from collections import defaultdict def extract_min(D, X): arg_min = -1 min_val = float('inf') for i in X: if D[i] < min_val: arg_min = i min_val = D[i] return arg_min class Graph: def __init__(self, length): self.length = length self.graph = defaultdict(list) def addEdge(self, u, v): self.graph[u].append(v) def Dijkstra(self, s): X = set(range(self.length)) D = [self.length + 1] * self.length P = [None] * self.length D[s] = 0 while X: u = extract_min(D, X) X.remove(u) for v in self.graph[u]: if v in X: new_dist = D[u] + 1 if D[v] > new_dist: D[v] = new_dist P[v] = u elif P[u] != v: return True, D[u] + D[v] + 1 return False, self.length n = int(input()) nums = list(map(int, input().split(' '))) a = [] for i in range(n): if nums[i] != 0: a.append(nums[i]) n = len(a) if n < 3: print(-1) elif n > 120: print(3) else: G = Graph(n) for i in range(n-1): for j in range(i+1, n): if a[i] & a[j] != 0: G.addEdge(i, j) G.addEdge(j, i) # print(G.graph) min_len = n + 1 for i in range(n): has_cycle, length = G.Dijkstra(i) if has_cycle and length < min_len: min_len = length if min_len == (n + 1): print(-1) else: print(min_len) ```
instruction
0
101,295
13
202,590
Yes
output
1
101,295
13
202,591
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given n integer numbers a_1, a_2, ..., a_n. Consider graph on n nodes, in which nodes i, j (i≠ j) are connected if and only if, a_i AND a_j≠ 0, where AND denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND). Find the length of the shortest cycle in this graph or determine that it doesn't have cycles at all. Input The first line contains one integer n (1 ≤ n ≤ 10^5) — number of numbers. The second line contains n integer numbers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^{18}). Output If the graph doesn't have any cycles, output -1. Else output the length of the shortest cycle. Examples Input 4 3 6 28 9 Output 4 Input 5 5 12 9 16 48 Output 3 Input 4 1 2 4 8 Output -1 Note In the first example, the shortest cycle is (9, 3, 6, 28). In the second example, the shortest cycle is (5, 12, 9). The graph has no cycles in the third example. Submitted Solution: ``` """This code was written by Russell Emerine - linguist, mathematician, coder, musician, and metalhead.""" n = int(input()) a = [] for x in input().split(): x = int(x) if x: a.append(x) n = len(a) edges = set() for d in range(64): p = 1 << d c = [] for i in range(n): x = a[i] if x & p: c.append(i) if len(c) > 2: import sys print(3) sys.exit() if len(c) == 2: edges.add((c[0], c[1])) m = n + 1 adj = [[][:] for _ in range(n)] for u, v in edges: adj[u].append(v) adj[v].append(u) from collections import deque for r in range(n): v = [False] * n p = [-1] * n d = [n + 1] * n d[r] = 0 s = deque([r]) while len(s): h = s.popleft() v[h] = True for c in adj[h]: if p[h] == c: continue elif v[c]: m = min(d[h] + 1 + d[c], m) else: d[c] = d[h] + 1 v[c] = True p[c] = h s.append(c); if m == n + 1: m = -1 print(m) ```
instruction
0
101,296
13
202,592
Yes
output
1
101,296
13
202,593
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given n integer numbers a_1, a_2, ..., a_n. Consider graph on n nodes, in which nodes i, j (i≠ j) are connected if and only if, a_i AND a_j≠ 0, where AND denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND). Find the length of the shortest cycle in this graph or determine that it doesn't have cycles at all. Input The first line contains one integer n (1 ≤ n ≤ 10^5) — number of numbers. The second line contains n integer numbers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^{18}). Output If the graph doesn't have any cycles, output -1. Else output the length of the shortest cycle. Examples Input 4 3 6 28 9 Output 4 Input 5 5 12 9 16 48 Output 3 Input 4 1 2 4 8 Output -1 Note In the first example, the shortest cycle is (9, 3, 6, 28). In the second example, the shortest cycle is (5, 12, 9). The graph has no cycles in the third example. Submitted Solution: ``` import sys, os, re, datetime, copy from collections import * from bisect import * def mat(v, *dims): def dim(i): return [copy.copy(v) for _ in range(dims[-1])] if i == len(dims)-1 else [dim(i+1) for _ in range(dims[i])] return dim(0) __cin__ = None def cin(): global __cin__ if __cin__ is None: __cin__ = iter(input().split(" ")) try: return next(__cin__) except StopIteration: __cin__ = iter(input().split(" ")) return next(__cin__) def iarr(n): return [int(cin()) for _ in range(n)] def farr(n): return [float(cin()) for _ in range(n)] def sarr(n): return [cin() for _ in range(n)] def carr(n): return input() def imat(n, m): return [iarr(m) for _ in range(n)] def fmat(n, m): return [farr(m) for _ in range(n)] def smat(n, m): return [sarr(m) for _ in range(n)] def cmat(n, m): return [input() for _ in range(n)] def bfs(i): dist = mat(INF, n) q = deque() q.append(i) dist[i] = 0 while len(q) > 0: u = q.popleft() for v in adj[u]: if dist[v] == INF: q.append(v) dist[v] = dist[u]+1 elif dist[v]+1 != dist[u]: return dist[v]+dist[u]+1 return INF N = 64 n = int(cin()) tmp = iarr(n) t = mat(0, N) g = mat([], N) adj = mat(set(), n) INF = 100000 ans = INF a = list(filter(lambda x: x > 0, tmp)) n = len(a) for j in range(N): for i in range(n): v = a[i] t[j] += (v>>j)&1 if t[j] >= 3: print("3") exit(0) if ((v>>j)&1) == 1: g[j].append(i) for i in range(N): if len(g[i]) == 2: adj[g[i][0]].add(g[i][1]) adj[g[i][1]].add(g[i][0]) for i in range(n): ans = min(ans, bfs(i)) print(-1 if ans == INF else ans) mmap = {0: "Hola", 1: "Mundo"} ```
instruction
0
101,297
13
202,594
Yes
output
1
101,297
13
202,595
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given n integer numbers a_1, a_2, ..., a_n. Consider graph on n nodes, in which nodes i, j (i≠ j) are connected if and only if, a_i AND a_j≠ 0, where AND denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND). Find the length of the shortest cycle in this graph or determine that it doesn't have cycles at all. Input The first line contains one integer n (1 ≤ n ≤ 10^5) — number of numbers. The second line contains n integer numbers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^{18}). Output If the graph doesn't have any cycles, output -1. Else output the length of the shortest cycle. Examples Input 4 3 6 28 9 Output 4 Input 5 5 12 9 16 48 Output 3 Input 4 1 2 4 8 Output -1 Note In the first example, the shortest cycle is (9, 3, 6, 28). In the second example, the shortest cycle is (5, 12, 9). The graph has no cycles in the third example. Submitted Solution: ``` import sys n = int(input()) data = [int(i) for i in input().split()] inf = 1 << 10 if n > 100: print(3) sys.exit() def bfs(a): layer = {a} parent = {a: -1} cnt = 0 while len(layer) > 0: # print(a, layer) cnt += 1 new = set() for l in layer: for v in data: if l & v and v != l and parent[l] != v: if v in layer: return 2 * cnt - 1 elif v in new: return 2 * cnt parent[v] = l new.add(v) # if v == a: # print(l, v) # print(parent) # return cnt # 5 # 5 12 9 16 48 layer = new return inf ans = inf for d in data: a2 = bfs(d) if a2 == inf: continue elif a2 == 3: print(3) sys.exit() elif a2 < ans: ans = a2 if ans == inf: print(-1) else: print(ans) ```
instruction
0
101,298
13
202,596
No
output
1
101,298
13
202,597
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given n integer numbers a_1, a_2, ..., a_n. Consider graph on n nodes, in which nodes i, j (i≠ j) are connected if and only if, a_i AND a_j≠ 0, where AND denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND). Find the length of the shortest cycle in this graph or determine that it doesn't have cycles at all. Input The first line contains one integer n (1 ≤ n ≤ 10^5) — number of numbers. The second line contains n integer numbers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^{18}). Output If the graph doesn't have any cycles, output -1. Else output the length of the shortest cycle. Examples Input 4 3 6 28 9 Output 4 Input 5 5 12 9 16 48 Output 3 Input 4 1 2 4 8 Output -1 Note In the first example, the shortest cycle is (9, 3, 6, 28). In the second example, the shortest cycle is (5, 12, 9). The graph has no cycles in the third example. Submitted Solution: ``` def bfs(g, src, dest): visited = {} dist = {} for i in g: visited[i] = False dist[i] = 1e18 dist[src] = 0 visited[src] = True q = [] q.append(src) while q: src = q.pop(0) for i in g[src]: if visited[i] == False: visited[i] = True dist[i] = min(dist[i], dist[src] + 1) q.append(i) return dist[dest] #print(timeit.timeit("c += 1", "c = 0", number = 100000000) n = int(input()) a = list(map(int, input().split())) c = 0 for i in range(64): c = 0 for j in range(n): if ((a[j] >> i) & 1): c += 1 if c == 3: break if c == 3: break if c == 3 or a == [565299879350784, 4508014854799360, 0, 0, 0, 4503635094929409, 18014810826352646, 306526525186934784, 0, 0]: print(3) else: g = {} #create adjacency list for i in range(64): buff = [-1, -1] for j in range(n): if (a[j] >> i) & 1: if buff[0] == -1: buff[0] = j elif buff[1] == -1: buff[1] = j if buff[0] not in g: g[buff[0]] = [] g[buff[0]].append(buff[1]) if buff[1] not in g: g[buff[1]] = [] g[buff[1]].append(buff[0]) #this completes our graph tg = {} dist = [] for i in g: for j in g[i]: tg = g tg[i].remove(j) tg[j].remove(i) dist.append( bfs(tg, i, j) ) if len(dist) != 0 and min(dist) < 1e18: print(min(dist) + 1) else: print(-1) ```
instruction
0
101,299
13
202,598
No
output
1
101,299
13
202,599
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given n integer numbers a_1, a_2, ..., a_n. Consider graph on n nodes, in which nodes i, j (i≠ j) are connected if and only if, a_i AND a_j≠ 0, where AND denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND). Find the length of the shortest cycle in this graph or determine that it doesn't have cycles at all. Input The first line contains one integer n (1 ≤ n ≤ 10^5) — number of numbers. The second line contains n integer numbers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^{18}). Output If the graph doesn't have any cycles, output -1. Else output the length of the shortest cycle. Examples Input 4 3 6 28 9 Output 4 Input 5 5 12 9 16 48 Output 3 Input 4 1 2 4 8 Output -1 Note In the first example, the shortest cycle is (9, 3, 6, 28). In the second example, the shortest cycle is (5, 12, 9). The graph has no cycles in the third example. Submitted Solution: ``` import math n = int(input()) a = list(map(int, input().split())) MAX_A = 10 ** 18 n_bits = math.ceil(math.log(MAX_A, 2)) + 1 if n > n_bits*3: print(3) exit(0) comp = [[] for _ in range(n_bits)] G = {} def add(v): G[v] = set() v2, i = v, 0 while v2 != 0: if v2 % 2 == 1: comp[i].append(v) v2 //= 2 i += 1 for v in a: add(v) for c in comp: if len(c) >= 3: print(3) exit(0) elif len(c) == 2: v, w = c G[v].add(w) G[w].add(v) res = -1 for u in a: level = {v:-1 for v in a} level[u] = 0 l = [u] i = 0 while len(l) > 0 and (res < 0 or 2*i < res): l2 = [] for v in l: for w in G[v]: if level[w] == -1: l2.append(w) level[w] = i+1 elif level[w] >= i: res = min(res, i+1+level[w]) if res > 0 else i+1+level[w] l = l2 i += 1 print(res) ```
instruction
0
101,300
13
202,600
No
output
1
101,300
13
202,601
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given n integer numbers a_1, a_2, ..., a_n. Consider graph on n nodes, in which nodes i, j (i≠ j) are connected if and only if, a_i AND a_j≠ 0, where AND denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND). Find the length of the shortest cycle in this graph or determine that it doesn't have cycles at all. Input The first line contains one integer n (1 ≤ n ≤ 10^5) — number of numbers. The second line contains n integer numbers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^{18}). Output If the graph doesn't have any cycles, output -1. Else output the length of the shortest cycle. Examples Input 4 3 6 28 9 Output 4 Input 5 5 12 9 16 48 Output 3 Input 4 1 2 4 8 Output -1 Note In the first example, the shortest cycle is (9, 3, 6, 28). In the second example, the shortest cycle is (5, 12, 9). The graph has no cycles in the third example. Submitted Solution: ``` """This code was written by Russell Emerine - linguist, mathematician, coder, musician, and metalhead.""" n = int(input()) a = [] for x in input().split(): x = int(x) if x: a.append(x) n = len(a) edges = set() for d in range(60): p = 1 << d c = [] for i in range(n): x = a[i] if x & p: c.append(i) if len(c) > 2: import sys print(3) sys.exit() if len(c) == 2: edges.add((c[0], c[1])) m = n + 1 adj = [[][:] for _ in range(n)] for u, v in edges: adj[u].append(v) adj[v].append(u) from collections import deque for r in range(n): v = [False] * n p = [-1] * n d = [n + 1] * n d[0] = 0 s = deque([r]) while len(s): h = s.popleft() v[h] = True for c in adj[h]: if p[h] == c: continue elif v[c]: m = min(d[h] + 1 + d[c], m) else: d[c] = d[h] + 1 v[c] = True p[c] = h s.append(c); if m == n + 1: m = -1 print(m) ```
instruction
0
101,301
13
202,602
No
output
1
101,301
13
202,603
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Let's define a non-oriented connected graph of n vertices and n - 1 edges as a beard, if all of its vertices except, perhaps, one, have the degree of 2 or 1 (that is, there exists no more than one vertex, whose degree is more than two). Let us remind you that the degree of a vertex is the number of edges that connect to it. Let each edge be either black or white. Initially all edges are black. You are given the description of the beard graph. Your task is to analyze requests of the following types: * paint the edge number i black. The edge number i is the edge that has this number in the description. It is guaranteed that by the moment of this request the i-th edge is white * paint the edge number i white. It is guaranteed that by the moment of this request the i-th edge is black * find the length of the shortest path going only along the black edges between vertices a and b or indicate that no such path exists between them (a path's length is the number of edges in it) The vertices are numbered with integers from 1 to n, and the edges are numbered with integers from 1 to n - 1. Input The first line of the input contains an integer n (2 ≤ n ≤ 105) — the number of vertices in the graph. Next n - 1 lines contain edges described as the numbers of vertices vi, ui (1 ≤ vi, ui ≤ n, vi ≠ ui) connected by this edge. It is guaranteed that the given graph is connected and forms a beard graph, and has no self-loops or multiple edges. The next line contains an integer m (1 ≤ m ≤ 3·105) — the number of requests. Next m lines contain requests in the following form: first a line contains an integer type, which takes values ​​from 1 to 3, and represents the request type. If type = 1, then the current request is a request to paint the edge black. In this case, in addition to number type the line should contain integer id (1 ≤ id ≤ n - 1), which represents the number of the edge to paint. If type = 2, then the current request is a request to paint the edge white, its form is similar to the previous request. If type = 3, then the current request is a request to find the distance. In this case, in addition to type, the line should contain two integers a, b (1 ≤ a, b ≤ n, a can be equal to b) — the numbers of vertices, the distance between which must be found. The numbers in all lines are separated by exactly one space. The edges are numbered in the order in which they are given in the input. Output For each request to "find the distance between vertices a and b" print the result. If there is no path going only along the black edges between vertices a and b, then print "-1" (without the quotes). Print the results in the order of receiving the requests, separate the numbers with spaces or line breaks. Examples Input 3 1 2 2 3 7 3 1 2 3 1 3 3 2 3 2 2 3 1 2 3 1 3 3 2 3 Output 1 2 1 1 -1 -1 Input 6 1 5 6 4 2 3 3 5 5 6 6 3 3 4 2 5 3 2 6 3 1 2 2 3 3 3 1 Output 3 -1 3 2 Note In the first sample vertices 1 and 2 are connected with edge number 1, and vertices 2 and 3 are connected with edge number 2. Before the repainting edge number 2 each vertex is reachable from each one along the black edges. Specifically, the shortest path between 1 and 3 goes along both edges. If we paint edge number 2 white, vertex 3 will end up cut off from other vertices, that is, no path exists from it to any other vertex along the black edges. Submitted Solution: ``` from sys import stdin, stdout def dfs(v, k, l): global d, t time[v][0] = t visit[v] = 1 distance[v] = l for u in vertices[v]: if not visit[u]: t += 1 d[(min(u, v), max(u, v))] = k k = dfs(u, k + 1, l + 1) time[v][1] = t t += 1 return k def translate(a, b): ans = [] for v in vertices[a]: if min(distance[a], distance[b]) <= distance[v] <= max(distance[a], distance[b]): ans.append(v) break for v in vertices[b]: if min(distance[a], distance[b]) <= distance[v] <= max(distance[a], distance[b]): ans.append(v) break return (d[(min(a, ans[0]), max(a, ans[0]))], d[(min(b, ans[1]), max(b, ans[1]))]) def update(n, value): tree[n + power - 1] = value n = n + power - 1 while n // 2: n //= 2 tree[n] = tree[n * 2] + tree[n * 2 + 1] def get(l, r, lb, rb, ind): if l == lb and r == rb: return tree[ind] m = (lb + rb) // 2 first, second = 0, 0 if l <= m: first = get(l, min(m, r), lb, m, ind * 2) if r > m: second = get(max(l, m + 1), r, m + 1, rb, ind * 2 + 1) return first + second n = int(stdin.readline()) vertices = [[] for i in range(n + 1)] time = [[0, 0] for i in range(n + 1)] challengers = [] root = 1 for i in range(n - 1): a, b = map(int, stdin.readline().split()) challengers.append((a, b)) vertices[a].append(b) vertices[b].append(a) for i in range(1, n + 1): if len(vertices[i]) > 2: root = i distance = {} d = {} t = 0 visit = [0 for i in range(n + 1)] dfs(root, 1, 0) power = 1 while power <= n: power *= 2 tree = [0 for i in range(2 * power)] q = int(stdin.readline()) for i in range(q): s = stdin.readline().split() if s[0] == '1': a, b = challengers[int(s[1]) - 1] update(d[(min(a, b), max(a, b))], 0) elif s[0] == '2': a, b = challengers[int(s[1]) - 1] update(d[(min(a, b), max(a, b))], 1) else: typ, a, b = map(int, s) if a == b: stdout.write('0\n') continue cnt = abs(distance[a] - distance[b]) if time[a][0] <= time[b][0] and time[a][1] >= time[b][1]: a, b = translate(a, b) if not get(a, b, 1, power, 1): stdout.write(str(cnt) + '\n') else: stdout.write('-1\n') elif time[a][0] >= time[b][0] and time[a][1] <= time[b][1]: a, b = translate(a, b) if not get(b, a, 1, power, 1): stdout.write(str(cnt) + '\n') else: stdout.write('-1\n') else: cnt = distance[a] + distance[b] a1, b1 = translate(root, a) a2, b2 = translate(root, b) if not get(a1, b1, 1, power, 1) and not get(a2, b2, 1, power, 1): stdout.write(str(cnt) + '\n') else: stdout.write('-1\n') ```
instruction
0
101,468
13
202,936
No
output
1
101,468
13
202,937
Provide tags and a correct Python 3 solution for this coding contest problem. After the piece of a devilish mirror hit the Kay's eye, he is no longer interested in the beauty of the roses. Now he likes to watch snowflakes. Once upon a time, he found a huge snowflake that has a form of the tree (connected acyclic graph) consisting of n nodes. The root of tree has index 1. Kay is very interested in the structure of this tree. After doing some research he formed q queries he is interested in. The i-th query asks to find a centroid of the subtree of the node vi. Your goal is to answer all queries. Subtree of a node is a part of tree consisting of this node and all it's descendants (direct or not). In other words, subtree of node v is formed by nodes u, such that node v is present on the path from u to root. Centroid of a tree (or a subtree) is a node, such that if we erase it from the tree, the maximum size of the connected component will be at least two times smaller than the size of the initial tree (or a subtree). Input The first line of the input contains two integers n and q (2 ≤ n ≤ 300 000, 1 ≤ q ≤ 300 000) — the size of the initial tree and the number of queries respectively. The second line contains n - 1 integer p2, p3, ..., pn (1 ≤ pi ≤ n) — the indices of the parents of the nodes from 2 to n. Node 1 is a root of the tree. It's guaranteed that pi define a correct tree. Each of the following q lines contain a single integer vi (1 ≤ vi ≤ n) — the index of the node, that define the subtree, for which we want to find a centroid. Output For each query print the index of a centroid of the corresponding subtree. If there are many suitable nodes, print any of them. It's guaranteed, that each subtree has at least one centroid. Example Input 7 4 1 1 3 3 5 3 1 2 3 5 Output 3 2 3 6 Note <image> The first query asks for a centroid of the whole tree — this is node 3. If we delete node 3 the tree will split in four components, two of size 1 and two of size 2. The subtree of the second node consists of this node only, so the answer is 2. Node 3 is centroid of its own subtree. The centroids of the subtree of the node 5 are nodes 5 and 6 — both answers are considered correct.
instruction
0
101,649
13
203,298
Tags: data structures, dfs and similar, dp, trees Correct Solution: ``` import operator import bisect n, q = [int(s) for s in input().split()] ps = [int(s) for s in input().split()] childs = [[] for _ in range(n)] for (c,pa) in enumerate(ps): childs[pa-1].append(c+1) toposort = [] this_level = [0] next_level = [] while len(this_level) > 0: for this_n in this_level: toposort.append(this_n) for c in childs[this_n]: next_level.append(c) this_level = next_level next_level = [] sz = [0]*n potentials = [0]*n potential_sz = [0]*n potential_lo = [0]*n centr = [0]*n for node in reversed(toposort): if len(childs[node]) == 0: centr[node] = node sz[node] = 1 else: s = 1 lg_c = -1 lg_c_sz = 0 for c in childs[node]: s += sz[c] if sz[c] > lg_c_sz: lg_c_sz = sz[c] lg_c = c sz[node] = s if lg_c_sz <= sz[node]//2: centr[node] = node potentials[node] = [node] potential_sz[node] = [sz[node]] continue potentials[node] = potentials[lg_c] potential_sz[node] = potential_sz[lg_c] i = bisect.bisect_right(potential_sz[node], sz[node]//2, lo=potential_lo[lg_c]) centr[node] = potentials[node][i] potentials[node].append(node) potential_lo[node] = i potential_sz[node].append(sz[node]) vs = [int(input()) - 1 for i in range(q)] print('\n'.join([str(centr[v]+1) for v in vs])) ```
output
1
101,649
13
203,299
Provide tags and a correct Python 3 solution for this coding contest problem. After the piece of a devilish mirror hit the Kay's eye, he is no longer interested in the beauty of the roses. Now he likes to watch snowflakes. Once upon a time, he found a huge snowflake that has a form of the tree (connected acyclic graph) consisting of n nodes. The root of tree has index 1. Kay is very interested in the structure of this tree. After doing some research he formed q queries he is interested in. The i-th query asks to find a centroid of the subtree of the node vi. Your goal is to answer all queries. Subtree of a node is a part of tree consisting of this node and all it's descendants (direct or not). In other words, subtree of node v is formed by nodes u, such that node v is present on the path from u to root. Centroid of a tree (or a subtree) is a node, such that if we erase it from the tree, the maximum size of the connected component will be at least two times smaller than the size of the initial tree (or a subtree). Input The first line of the input contains two integers n and q (2 ≤ n ≤ 300 000, 1 ≤ q ≤ 300 000) — the size of the initial tree and the number of queries respectively. The second line contains n - 1 integer p2, p3, ..., pn (1 ≤ pi ≤ n) — the indices of the parents of the nodes from 2 to n. Node 1 is a root of the tree. It's guaranteed that pi define a correct tree. Each of the following q lines contain a single integer vi (1 ≤ vi ≤ n) — the index of the node, that define the subtree, for which we want to find a centroid. Output For each query print the index of a centroid of the corresponding subtree. If there are many suitable nodes, print any of them. It's guaranteed, that each subtree has at least one centroid. Example Input 7 4 1 1 3 3 5 3 1 2 3 5 Output 3 2 3 6 Note <image> The first query asks for a centroid of the whole tree — this is node 3. If we delete node 3 the tree will split in four components, two of size 1 and two of size 2. The subtree of the second node consists of this node only, so the answer is 2. Node 3 is centroid of its own subtree. The centroids of the subtree of the node 5 are nodes 5 and 6 — both answers are considered correct.
instruction
0
101,650
13
203,300
Tags: data structures, dfs and similar, dp, trees Correct Solution: ``` def main(): import sys E=sys.stdin R=E.readline n,q=map(int,R().split()) P=[0,0]+[int(i) for i in R().split()] #n=q=300000 #P=[0]+list(range(n)) #exit() C=[[]] i=0 while i<n: i+=1 C.append([]) i=2 j=len(P) while i<j: C[P[i]].append(i) i+=1 i=Qi=0 W=[0]*(n+1) S=[0]*(n+1) Q=[0]*(n+1) while i<n: i+=1 W[i]=len(C[i]) if W[i]==0: Q[Qi]=i Qi+=1 A=[0]*(n+1) while Qi: Qi-=1 x=Q[Qi] S[x]+=1 if P[x]: y=P[x] S[y]+=S[x] W[y]-=1 if W[y]==0: Q[Qi]=y Qi+=1 a=S[x]>>1 A[x]=x for z in C[x]: if S[z]>a: A[x]=A[z] b=S[x]-S[A[x]] while b>a: A[x]=P[A[x]] b=S[x]-S[A[x]] break while q: q-=1 sys.stdout.write(str(A[int(R())])+'\n') main() ```
output
1
101,650
13
203,301
Provide tags and a correct Python 3 solution for this coding contest problem. After the piece of a devilish mirror hit the Kay's eye, he is no longer interested in the beauty of the roses. Now he likes to watch snowflakes. Once upon a time, he found a huge snowflake that has a form of the tree (connected acyclic graph) consisting of n nodes. The root of tree has index 1. Kay is very interested in the structure of this tree. After doing some research he formed q queries he is interested in. The i-th query asks to find a centroid of the subtree of the node vi. Your goal is to answer all queries. Subtree of a node is a part of tree consisting of this node and all it's descendants (direct or not). In other words, subtree of node v is formed by nodes u, such that node v is present on the path from u to root. Centroid of a tree (or a subtree) is a node, such that if we erase it from the tree, the maximum size of the connected component will be at least two times smaller than the size of the initial tree (or a subtree). Input The first line of the input contains two integers n and q (2 ≤ n ≤ 300 000, 1 ≤ q ≤ 300 000) — the size of the initial tree and the number of queries respectively. The second line contains n - 1 integer p2, p3, ..., pn (1 ≤ pi ≤ n) — the indices of the parents of the nodes from 2 to n. Node 1 is a root of the tree. It's guaranteed that pi define a correct tree. Each of the following q lines contain a single integer vi (1 ≤ vi ≤ n) — the index of the node, that define the subtree, for which we want to find a centroid. Output For each query print the index of a centroid of the corresponding subtree. If there are many suitable nodes, print any of them. It's guaranteed, that each subtree has at least one centroid. Example Input 7 4 1 1 3 3 5 3 1 2 3 5 Output 3 2 3 6 Note <image> The first query asks for a centroid of the whole tree — this is node 3. If we delete node 3 the tree will split in four components, two of size 1 and two of size 2. The subtree of the second node consists of this node only, so the answer is 2. Node 3 is centroid of its own subtree. The centroids of the subtree of the node 5 are nodes 5 and 6 — both answers are considered correct.
instruction
0
101,651
13
203,302
Tags: data structures, dfs and similar, dp, trees Correct Solution: ``` # [https://codeforces.com/contest/685/submission/42128998 <- https://codeforces.com/contest/685/status/B <- https://codeforces.com/contest/685 <- https://codeforces.com/blog/entry/45556 <- https://codeforces.com/problemset/problem/685/B <- https://algoprog.ru/material/pc685pB] import bisect n, q = [int(s) for s in input().split()] ps = [int(s) for s in input().split()] childs = [[] for _ in range(n)] for (c,pa) in enumerate(ps): childs[pa-1].append(c+1) toposort = [] this_level = [0] next_level = [] while len(this_level) > 0: for this_n in this_level: toposort.append(this_n) for c in childs[this_n]: next_level.append(c) this_level = next_level next_level = [] sz = [0]*n potentials = [0]*n potential_sz = [0]*n potential_lo = [0]*n centr = [0]*n for node in reversed(toposort): if len(childs[node]) == 0: centr[node] = node sz[node] = 1 else: s = 1 lg_c = -1 lg_c_sz = 0 for c in childs[node]: s += sz[c] if sz[c] > lg_c_sz: lg_c_sz = sz[c] lg_c = c sz[node] = s if lg_c_sz <= sz[node]//2: centr[node] = node potentials[node] = [node] potential_sz[node] = [sz[node]] continue potentials[node] = potentials[lg_c] potential_sz[node] = potential_sz[lg_c] i = bisect.bisect_right(potential_sz[node], sz[node]//2, lo=potential_lo[lg_c]) centr[node] = potentials[node][i] potentials[node].append(node) potential_lo[node] = i potential_sz[node].append(sz[node]) vs = [int(input()) - 1 for i in range(q)] print('\n'.join([str(centr[v]+1) for v in vs])) ```
output
1
101,651
13
203,303
Provide tags and a correct Python 3 solution for this coding contest problem. After the piece of a devilish mirror hit the Kay's eye, he is no longer interested in the beauty of the roses. Now he likes to watch snowflakes. Once upon a time, he found a huge snowflake that has a form of the tree (connected acyclic graph) consisting of n nodes. The root of tree has index 1. Kay is very interested in the structure of this tree. After doing some research he formed q queries he is interested in. The i-th query asks to find a centroid of the subtree of the node vi. Your goal is to answer all queries. Subtree of a node is a part of tree consisting of this node and all it's descendants (direct or not). In other words, subtree of node v is formed by nodes u, such that node v is present on the path from u to root. Centroid of a tree (or a subtree) is a node, such that if we erase it from the tree, the maximum size of the connected component will be at least two times smaller than the size of the initial tree (or a subtree). Input The first line of the input contains two integers n and q (2 ≤ n ≤ 300 000, 1 ≤ q ≤ 300 000) — the size of the initial tree and the number of queries respectively. The second line contains n - 1 integer p2, p3, ..., pn (1 ≤ pi ≤ n) — the indices of the parents of the nodes from 2 to n. Node 1 is a root of the tree. It's guaranteed that pi define a correct tree. Each of the following q lines contain a single integer vi (1 ≤ vi ≤ n) — the index of the node, that define the subtree, for which we want to find a centroid. Output For each query print the index of a centroid of the corresponding subtree. If there are many suitable nodes, print any of them. It's guaranteed, that each subtree has at least one centroid. Example Input 7 4 1 1 3 3 5 3 1 2 3 5 Output 3 2 3 6 Note <image> The first query asks for a centroid of the whole tree — this is node 3. If we delete node 3 the tree will split in four components, two of size 1 and two of size 2. The subtree of the second node consists of this node only, so the answer is 2. Node 3 is centroid of its own subtree. The centroids of the subtree of the node 5 are nodes 5 and 6 — both answers are considered correct.
instruction
0
101,652
13
203,304
Tags: data structures, dfs and similar, dp, trees Correct Solution: ``` import operator import bisect n, q = [int(s) for s in input().split()] ps = [int(s) for s in input().split()] childs = [[] for _ in range(n)] for (c,pa) in enumerate(ps): childs[pa-1].append(c+1) toposort = [] this_level = [0] next_level = [] while len(this_level) > 0: for this_n in this_level: toposort.append(this_n) for c in childs[this_n]: next_level.append(c) this_level = next_level next_level = [] sz = [0]*n potentials = [0]*n potential_sz = [0]*n potential_lo = [0]*n centr = [0]*n for node in reversed(toposort): if len(childs[node]) == 0: centr[node] = node sz[node] = 1 else: s = 1 lg_c = -1 lg_c_sz = 0 for c in childs[node]: s += sz[c] if sz[c] > lg_c_sz: lg_c_sz = sz[c] lg_c = c sz[node] = s if lg_c_sz <= sz[node]//2: centr[node] = node potentials[node] = [node] potential_sz[node] = [sz[node]] continue potentials[node] = potentials[lg_c] potential_sz[node] = potential_sz[lg_c] i = bisect.bisect_right(potential_sz[node], sz[node]//2, lo=potential_lo[lg_c]) centr[node] = potentials[node][i] potentials[node].append(node) potential_lo[node] = i potential_sz[node].append(sz[node]) vs = [int(input()) - 1 for i in range(q)] print('\n'.join([str(centr[v]+1) for v in vs])) # Made By Mostafa_Khaled ```
output
1
101,652
13
203,305
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. After the piece of a devilish mirror hit the Kay's eye, he is no longer interested in the beauty of the roses. Now he likes to watch snowflakes. Once upon a time, he found a huge snowflake that has a form of the tree (connected acyclic graph) consisting of n nodes. The root of tree has index 1. Kay is very interested in the structure of this tree. After doing some research he formed q queries he is interested in. The i-th query asks to find a centroid of the subtree of the node vi. Your goal is to answer all queries. Subtree of a node is a part of tree consisting of this node and all it's descendants (direct or not). In other words, subtree of node v is formed by nodes u, such that node v is present on the path from u to root. Centroid of a tree (or a subtree) is a node, such that if we erase it from the tree, the maximum size of the connected component will be at least two times smaller than the size of the initial tree (or a subtree). Input The first line of the input contains two integers n and q (2 ≤ n ≤ 300 000, 1 ≤ q ≤ 300 000) — the size of the initial tree and the number of queries respectively. The second line contains n - 1 integer p2, p3, ..., pn (1 ≤ pi ≤ n) — the indices of the parents of the nodes from 2 to n. Node 1 is a root of the tree. It's guaranteed that pi define a correct tree. Each of the following q lines contain a single integer vi (1 ≤ vi ≤ n) — the index of the node, that define the subtree, for which we want to find a centroid. Output For each query print the index of a centroid of the corresponding subtree. If there are many suitable nodes, print any of them. It's guaranteed, that each subtree has at least one centroid. Example Input 7 4 1 1 3 3 5 3 1 2 3 5 Output 3 2 3 6 Note <image> The first query asks for a centroid of the whole tree — this is node 3. If we delete node 3 the tree will split in four components, two of size 1 and two of size 2. The subtree of the second node consists of this node only, so the answer is 2. Node 3 is centroid of its own subtree. The centroids of the subtree of the node 5 are nodes 5 and 6 — both answers are considered correct. Submitted Solution: ``` import sys def main(): x = sys.stdin.readline().split() n,r = int(x[0]),int(x[1]) x = list(map(int, sys.stdin.readline().split())) s = [ [] for i in range(n)] for i in range(n-1): s[x[i]-1].append(i+1) ch = [0]*n q = [0] u = [False]*n while len(q)!=0: c = q[len(q)-1] added = False for a in s[c]: if not u[a]: q.append(a) added = True if added: continue q.pop() u[c] = True count = 1 for a in s[c]: count+=ch[a] ch[c] = count ev = [i for i in range(n)] q = [0] w = [0] wi =0 while len(q)!=0: c = q.pop() p = ch[c]/2 for a in s[c]: if ch[a]>p: q.append(a) w.append(a) break ok = True while ok and len(w)>wi: ok = False if ch[c] <= ch[w[wi]]/2 or len(q)==0: ok=True ev[w[wi]] = c wi+=1 ans = [] for i in range(r): qi = int(sys.stdin.readline()) ans.append(str(ev[qi-1]+1)) print('\n'.join(ans)) main() ```
instruction
0
101,653
13
203,306
No
output
1
101,653
13
203,307
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. After the piece of a devilish mirror hit the Kay's eye, he is no longer interested in the beauty of the roses. Now he likes to watch snowflakes. Once upon a time, he found a huge snowflake that has a form of the tree (connected acyclic graph) consisting of n nodes. The root of tree has index 1. Kay is very interested in the structure of this tree. After doing some research he formed q queries he is interested in. The i-th query asks to find a centroid of the subtree of the node vi. Your goal is to answer all queries. Subtree of a node is a part of tree consisting of this node and all it's descendants (direct or not). In other words, subtree of node v is formed by nodes u, such that node v is present on the path from u to root. Centroid of a tree (or a subtree) is a node, such that if we erase it from the tree, the maximum size of the connected component will be at least two times smaller than the size of the initial tree (or a subtree). Input The first line of the input contains two integers n and q (2 ≤ n ≤ 300 000, 1 ≤ q ≤ 300 000) — the size of the initial tree and the number of queries respectively. The second line contains n - 1 integer p2, p3, ..., pn (1 ≤ pi ≤ n) — the indices of the parents of the nodes from 2 to n. Node 1 is a root of the tree. It's guaranteed that pi define a correct tree. Each of the following q lines contain a single integer vi (1 ≤ vi ≤ n) — the index of the node, that define the subtree, for which we want to find a centroid. Output For each query print the index of a centroid of the corresponding subtree. If there are many suitable nodes, print any of them. It's guaranteed, that each subtree has at least one centroid. Example Input 7 4 1 1 3 3 5 3 1 2 3 5 Output 3 2 3 6 Note <image> The first query asks for a centroid of the whole tree — this is node 3. If we delete node 3 the tree will split in four components, two of size 1 and two of size 2. The subtree of the second node consists of this node only, so the answer is 2. Node 3 is centroid of its own subtree. The centroids of the subtree of the node 5 are nodes 5 and 6 — both answers are considered correct. Submitted Solution: ``` class Node: def __init__(self, ind): if (flag): print("init") self.index = ind self.children = [] def addChild(self, node): if (flag): print("addChild") self.children.append(node) def countV(self): if (flag): print("countV") cnt = 1 for vertex in self.children: cnt += vertex.countV() self.count = cnt return cnt def centroid(self): if (flag): print("centroid") curr = self max = self.count / 2 while True: sut = False for child in curr.children: if (child.count > max): curr = child sut = True break if (not sut): return curr.index st = input().split(" ") n = int(st[0]) q = int(st[1]) flag = n > 200000 p = input().split(" ") arr = [] for i in range(1, n + 1): arr.append(Node(i)) if (flag): print("before") index_vertex = 1 for index_parent2 in p: if (flag): print("process " + index_parent2) index_parent = int(index_parent2) - 1 arr[index_vertex].parent = index_parent arr[index_parent].addChild(arr[index_vertex]) index_vertex += 1 arr[0].countV() q_c = 0 while q_c < q: if (flag): print(arr[int(input()) - 1].centroid()) q_c += 1 ```
instruction
0
101,654
13
203,308
No
output
1
101,654
13
203,309
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. After the piece of a devilish mirror hit the Kay's eye, he is no longer interested in the beauty of the roses. Now he likes to watch snowflakes. Once upon a time, he found a huge snowflake that has a form of the tree (connected acyclic graph) consisting of n nodes. The root of tree has index 1. Kay is very interested in the structure of this tree. After doing some research he formed q queries he is interested in. The i-th query asks to find a centroid of the subtree of the node vi. Your goal is to answer all queries. Subtree of a node is a part of tree consisting of this node and all it's descendants (direct or not). In other words, subtree of node v is formed by nodes u, such that node v is present on the path from u to root. Centroid of a tree (or a subtree) is a node, such that if we erase it from the tree, the maximum size of the connected component will be at least two times smaller than the size of the initial tree (or a subtree). Input The first line of the input contains two integers n and q (2 ≤ n ≤ 300 000, 1 ≤ q ≤ 300 000) — the size of the initial tree and the number of queries respectively. The second line contains n - 1 integer p2, p3, ..., pn (1 ≤ pi ≤ n) — the indices of the parents of the nodes from 2 to n. Node 1 is a root of the tree. It's guaranteed that pi define a correct tree. Each of the following q lines contain a single integer vi (1 ≤ vi ≤ n) — the index of the node, that define the subtree, for which we want to find a centroid. Output For each query print the index of a centroid of the corresponding subtree. If there are many suitable nodes, print any of them. It's guaranteed, that each subtree has at least one centroid. Example Input 7 4 1 1 3 3 5 3 1 2 3 5 Output 3 2 3 6 Note <image> The first query asks for a centroid of the whole tree — this is node 3. If we delete node 3 the tree will split in four components, two of size 1 and two of size 2. The subtree of the second node consists of this node only, so the answer is 2. Node 3 is centroid of its own subtree. The centroids of the subtree of the node 5 are nodes 5 and 6 — both answers are considered correct. Submitted Solution: ``` import operator import bisect n, q = [int(s) for s in input().split()] ps = [int(s) for s in input().split()] childs = [[] for _ in range(n)] for (c,pa) in enumerate(ps): childs[pa-1].append(c+1) toposort = [] this_level = [0] next_level = [] while len(this_level) > 0: for this_n in this_level: toposort.append(this_n) for c in childs[this_n]: next_level.append(c) this_level = next_level next_level = [] sz = [0]*n potentials = {} potential_sz = {} centr = [-1]*n for node in reversed(toposort): if len(childs[node]) == 0: centr[node] = node potentials[node] = [] sz[node] = 1 else: sz[node] = 1 + sum(sz[c] for c in childs[node]) lg_c, lg_c_sz = max( ((c, sz[c]) for c in childs[node]), key=operator.itemgetter(1) ) if lg_c_sz <= sz[node]/2: centr[node] = node potentials[node] = [node] potential_sz[node] = [sz[node]] continue potentials[node] = potentials[lg_c] potential_sz[node] = potential_sz[lg_c] i = bisect.bisect_right(potential_sz[node], sz[node]/2) centr[node] = potentials[node][i] potentials[node].append(node) potential_sz[node].append(sz[node]) def find_centroid(v, baggage): if v not in lg_c: return v if baggage + (sz[v]-lg_sz[v]) >= lg_sz[v]: return v return find_centroid(lg_c[v], baggage + (sz[v] - lg_sz[v])) vs = [] for i in range(q): vs.append(int(input()) - 1) print(*vs, sep='\n') ```
instruction
0
101,655
13
203,310
No
output
1
101,655
13
203,311
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. After the piece of a devilish mirror hit the Kay's eye, he is no longer interested in the beauty of the roses. Now he likes to watch snowflakes. Once upon a time, he found a huge snowflake that has a form of the tree (connected acyclic graph) consisting of n nodes. The root of tree has index 1. Kay is very interested in the structure of this tree. After doing some research he formed q queries he is interested in. The i-th query asks to find a centroid of the subtree of the node vi. Your goal is to answer all queries. Subtree of a node is a part of tree consisting of this node and all it's descendants (direct or not). In other words, subtree of node v is formed by nodes u, such that node v is present on the path from u to root. Centroid of a tree (or a subtree) is a node, such that if we erase it from the tree, the maximum size of the connected component will be at least two times smaller than the size of the initial tree (or a subtree). Input The first line of the input contains two integers n and q (2 ≤ n ≤ 300 000, 1 ≤ q ≤ 300 000) — the size of the initial tree and the number of queries respectively. The second line contains n - 1 integer p2, p3, ..., pn (1 ≤ pi ≤ n) — the indices of the parents of the nodes from 2 to n. Node 1 is a root of the tree. It's guaranteed that pi define a correct tree. Each of the following q lines contain a single integer vi (1 ≤ vi ≤ n) — the index of the node, that define the subtree, for which we want to find a centroid. Output For each query print the index of a centroid of the corresponding subtree. If there are many suitable nodes, print any of them. It's guaranteed, that each subtree has at least one centroid. Example Input 7 4 1 1 3 3 5 3 1 2 3 5 Output 3 2 3 6 Note <image> The first query asks for a centroid of the whole tree — this is node 3. If we delete node 3 the tree will split in four components, two of size 1 and two of size 2. The subtree of the second node consists of this node only, so the answer is 2. Node 3 is centroid of its own subtree. The centroids of the subtree of the node 5 are nodes 5 and 6 — both answers are considered correct. Submitted Solution: ``` import sys import threading sys.setrecursionlimit(200000) class Node: def __init__(self, ind): self.index = ind self.children = [] self.max_child = 0 def addChild(self, node): self.children.append(node) if (self.max_child == 0 or type(self.max_child) == Node and self.max_child.count < node.count): self.max_child = node def countV(self): cnt = 1 for vertex in self.children: cnt += vertex.countV() self.count = cnt return cnt def centroid(self): curr = self max = self.count / 2 while True: # sut = False child = self.max_child if (child.count > max): curr = child else: return curr.index # for child in curr.children: # if (child.count > max): # curr = child # sut = True # break # if (not sut): # return curr.index class Run: def __call__(self): st = input().split(" ") n = int(st[0]) q = int(st[1]) # flag = n > 200000 p = input().split(" ") arr = [] for i in range(1, n + 1): arr.append(Node(i)) index_vertex = 1 for index_parent2 in p: index_parent = int(index_parent2) - 1 arr[index_vertex].parent = index_parent arr[index_parent].addChild(arr[index_vertex]) index_vertex += 1 # try: arr[0].countV() # except BaseException as err: # print(err) # print(type(err)) # if (flag): print("before") q_c = 0 while q_c < q: # if (flag): print("after") print(arr[int(input()) - 1].centroid()) q_c += 1 threading.stack_size(0x2000000) t = threading.Thread(target=Run()) t.start() t.join() ```
instruction
0
101,656
13
203,312
No
output
1
101,656
13
203,313
Provide a correct Python 3 solution for this coding contest problem. We have a tree with N vertices. The vertices are numbered 0 through N - 1, and the i-th edge (0 ≤ i < N - 1) comnnects Vertex a_i and b_i. For each pair of vertices u and v (0 ≤ u, v < N), we define the distance d(u, v) as the number of edges in the path u-v. It is expected that one of the vertices will be invaded by aliens from outer space. Snuke wants to immediately identify that vertex when the invasion happens. To do so, he has decided to install an antenna on some vertices. First, he decides the number of antennas, K (1 ≤ K ≤ N). Then, he chooses K different vertices, x_0, x_1, ..., x_{K - 1}, on which he installs Antenna 0, 1, ..., K - 1, respectively. If Vertex v is invaded by aliens, Antenna k (0 ≤ k < K) will output the distance d(x_k, v). Based on these K outputs, Snuke will identify the vertex that is invaded. Thus, in order to identify the invaded vertex no matter which one is invaded, the following condition must hold: * For each vertex u (0 ≤ u < N), consider the vector (d(x_0, u), ..., d(x_{K - 1}, u)). These N vectors are distinct. Find the minumum value of K, the number of antennas, when the condition is satisfied. Constraints * 2 ≤ N ≤ 10^5 * 0 ≤ a_i, b_i < N * The given graph is a tree. Input Input is given from Standard Input in the following format: N a_0 b_0 a_1 b_1 : a_{N - 2} b_{N - 2} Output Print the minumum value of K, the number of antennas, when the condition is satisfied. Examples Input 5 0 1 0 2 0 3 3 4 Output 2 Input 2 0 1 Output 1 Input 10 2 8 6 0 4 1 7 6 2 3 8 6 6 9 2 4 5 8 Output 3
instruction
0
101,888
13
203,776
"Correct Solution: ``` def main(): n = int(input()) ab = [list(map(int, input().split())) for _ in [0]*(n-1)] g = [[] for _ in [0]*n] [g[a].append(b) for a, b in ab] [g[b].append(a) for a, b in ab] for i in range(n): if len(g[i]) > 2: root = i break else: print(1) return d = [-1]*n # 根からの距離 d[root] = 0 q = [root] cnt = 0 while q: # BFS cnt += 1 qq = [] while q: i = q.pop() for j in g[i]: if d[j] == -1: d[j] = cnt qq.append(j) q = qq d2 = sorted([(j, i) for i, j in enumerate(d)])[::-1] stock = [0]*n ans = 0 for _, i in d2: dist = d[i] s = 0 cnt = 0 for j in g[i]: if dist < d[j]: s += stock[j] cnt += 1 ans += max(cnt-s-1, 0) s += max(cnt-s-1, 0) if s > 0 or cnt > 1: stock[i] = 1 print(ans) main() ```
output
1
101,888
13
203,777
Provide a correct Python 3 solution for this coding contest problem. We have a tree with N vertices. The vertices are numbered 0 through N - 1, and the i-th edge (0 ≤ i < N - 1) comnnects Vertex a_i and b_i. For each pair of vertices u and v (0 ≤ u, v < N), we define the distance d(u, v) as the number of edges in the path u-v. It is expected that one of the vertices will be invaded by aliens from outer space. Snuke wants to immediately identify that vertex when the invasion happens. To do so, he has decided to install an antenna on some vertices. First, he decides the number of antennas, K (1 ≤ K ≤ N). Then, he chooses K different vertices, x_0, x_1, ..., x_{K - 1}, on which he installs Antenna 0, 1, ..., K - 1, respectively. If Vertex v is invaded by aliens, Antenna k (0 ≤ k < K) will output the distance d(x_k, v). Based on these K outputs, Snuke will identify the vertex that is invaded. Thus, in order to identify the invaded vertex no matter which one is invaded, the following condition must hold: * For each vertex u (0 ≤ u < N), consider the vector (d(x_0, u), ..., d(x_{K - 1}, u)). These N vectors are distinct. Find the minumum value of K, the number of antennas, when the condition is satisfied. Constraints * 2 ≤ N ≤ 10^5 * 0 ≤ a_i, b_i < N * The given graph is a tree. Input Input is given from Standard Input in the following format: N a_0 b_0 a_1 b_1 : a_{N - 2} b_{N - 2} Output Print the minumum value of K, the number of antennas, when the condition is satisfied. Examples Input 5 0 1 0 2 0 3 3 4 Output 2 Input 2 0 1 Output 1 Input 10 2 8 6 0 4 1 7 6 2 3 8 6 6 9 2 4 5 8 Output 3
instruction
0
101,889
13
203,778
"Correct Solution: ``` import math #import numpy as np import queue from collections import deque,defaultdict import heapq from sys import stdin,setrecursionlimit #from scipy.sparse.csgraph import dijkstra #from scipy.sparse import csr_matrix ipt = stdin.readline setrecursionlimit(10**7) def main(): n = int(ipt()) way = [[] for i in range(n)] for _ in [0]*(n-1): a,b = map(int,ipt().split()) way[a].append(b) way[b].append(a) rt = -1 for i in range(n): if len(way[i]) > 2: rt = i break def dp(pp,np): sum = 0 n0 = 0 for i in way[np]: if i == pp: continue tmp = dp(np,i) sum += tmp if tmp == 0: n0 += 1 if n0 > 1: sum += n0-1 return sum if rt == -1: print(1) exit() else: print(dp(-1,rt)) return if __name__ == '__main__': main() ```
output
1
101,889
13
203,779
Provide a correct Python 3 solution for this coding contest problem. We have a tree with N vertices. The vertices are numbered 0 through N - 1, and the i-th edge (0 ≤ i < N - 1) comnnects Vertex a_i and b_i. For each pair of vertices u and v (0 ≤ u, v < N), we define the distance d(u, v) as the number of edges in the path u-v. It is expected that one of the vertices will be invaded by aliens from outer space. Snuke wants to immediately identify that vertex when the invasion happens. To do so, he has decided to install an antenna on some vertices. First, he decides the number of antennas, K (1 ≤ K ≤ N). Then, he chooses K different vertices, x_0, x_1, ..., x_{K - 1}, on which he installs Antenna 0, 1, ..., K - 1, respectively. If Vertex v is invaded by aliens, Antenna k (0 ≤ k < K) will output the distance d(x_k, v). Based on these K outputs, Snuke will identify the vertex that is invaded. Thus, in order to identify the invaded vertex no matter which one is invaded, the following condition must hold: * For each vertex u (0 ≤ u < N), consider the vector (d(x_0, u), ..., d(x_{K - 1}, u)). These N vectors are distinct. Find the minumum value of K, the number of antennas, when the condition is satisfied. Constraints * 2 ≤ N ≤ 10^5 * 0 ≤ a_i, b_i < N * The given graph is a tree. Input Input is given from Standard Input in the following format: N a_0 b_0 a_1 b_1 : a_{N - 2} b_{N - 2} Output Print the minumum value of K, the number of antennas, when the condition is satisfied. Examples Input 5 0 1 0 2 0 3 3 4 Output 2 Input 2 0 1 Output 1 Input 10 2 8 6 0 4 1 7 6 2 3 8 6 6 9 2 4 5 8 Output 3
instruction
0
101,890
13
203,780
"Correct Solution: ``` import sys sys.setrecursionlimit(100000) def dfs(v, p, links): lv = links[v] if len(lv) == 1: return 0 cnt0 = 0 ret = 0 for l in lv: if l == p: continue res = dfs(l, v, links) ret += res if res == 0: cnt0 += 1 if cnt0: ret += cnt0 - 1 return ret def solve(n, links): if n == 2: return 1 for i, l in enumerate(links): if len(l) > 2: return dfs(i, None, links) else: return 1 n = int(input()) links = [set() for _ in range(n)] for _ in range(n - 1): a, b = map(int, input().split()) links[a].add(b) links[b].add(a) print(solve(n, links)) ```
output
1
101,890
13
203,781
Provide a correct Python 3 solution for this coding contest problem. We have a tree with N vertices. The vertices are numbered 0 through N - 1, and the i-th edge (0 ≤ i < N - 1) comnnects Vertex a_i and b_i. For each pair of vertices u and v (0 ≤ u, v < N), we define the distance d(u, v) as the number of edges in the path u-v. It is expected that one of the vertices will be invaded by aliens from outer space. Snuke wants to immediately identify that vertex when the invasion happens. To do so, he has decided to install an antenna on some vertices. First, he decides the number of antennas, K (1 ≤ K ≤ N). Then, he chooses K different vertices, x_0, x_1, ..., x_{K - 1}, on which he installs Antenna 0, 1, ..., K - 1, respectively. If Vertex v is invaded by aliens, Antenna k (0 ≤ k < K) will output the distance d(x_k, v). Based on these K outputs, Snuke will identify the vertex that is invaded. Thus, in order to identify the invaded vertex no matter which one is invaded, the following condition must hold: * For each vertex u (0 ≤ u < N), consider the vector (d(x_0, u), ..., d(x_{K - 1}, u)). These N vectors are distinct. Find the minumum value of K, the number of antennas, when the condition is satisfied. Constraints * 2 ≤ N ≤ 10^5 * 0 ≤ a_i, b_i < N * The given graph is a tree. Input Input is given from Standard Input in the following format: N a_0 b_0 a_1 b_1 : a_{N - 2} b_{N - 2} Output Print the minumum value of K, the number of antennas, when the condition is satisfied. Examples Input 5 0 1 0 2 0 3 3 4 Output 2 Input 2 0 1 Output 1 Input 10 2 8 6 0 4 1 7 6 2 3 8 6 6 9 2 4 5 8 Output 3
instruction
0
101,891
13
203,782
"Correct Solution: ``` # 大混乱したので乱択 # これ嘘じゃないのか??? def main(): import sys sys.setrecursionlimit(500000) N = int(input()) if N==2: print(1) exit() E = [[] for _ in range(N)] for _ in range(N-1): a, b = map(int, input().split()) E[a].append(b) E[b].append(a) def dfs(v=0, p=-1, root=0): cnt_child = 0 cnt_false = 0 res = 0 for u in E[v]: if u!=p: cnt_child += 1 d = dfs(u, v, root) res += d cnt_false += d == 0 return res + max(0, cnt_false - 1) #for i in range(N): # print(dfs(i, -1, i)) print(max(dfs(i, -1, i) for i in sorted(range(N), key=lambda x: -len(E[x]))[:1])) main() ```
output
1
101,891
13
203,783
Provide a correct Python 3 solution for this coding contest problem. We have a tree with N vertices. The vertices are numbered 0 through N - 1, and the i-th edge (0 ≤ i < N - 1) comnnects Vertex a_i and b_i. For each pair of vertices u and v (0 ≤ u, v < N), we define the distance d(u, v) as the number of edges in the path u-v. It is expected that one of the vertices will be invaded by aliens from outer space. Snuke wants to immediately identify that vertex when the invasion happens. To do so, he has decided to install an antenna on some vertices. First, he decides the number of antennas, K (1 ≤ K ≤ N). Then, he chooses K different vertices, x_0, x_1, ..., x_{K - 1}, on which he installs Antenna 0, 1, ..., K - 1, respectively. If Vertex v is invaded by aliens, Antenna k (0 ≤ k < K) will output the distance d(x_k, v). Based on these K outputs, Snuke will identify the vertex that is invaded. Thus, in order to identify the invaded vertex no matter which one is invaded, the following condition must hold: * For each vertex u (0 ≤ u < N), consider the vector (d(x_0, u), ..., d(x_{K - 1}, u)). These N vectors are distinct. Find the minumum value of K, the number of antennas, when the condition is satisfied. Constraints * 2 ≤ N ≤ 10^5 * 0 ≤ a_i, b_i < N * The given graph is a tree. Input Input is given from Standard Input in the following format: N a_0 b_0 a_1 b_1 : a_{N - 2} b_{N - 2} Output Print the minumum value of K, the number of antennas, when the condition is satisfied. Examples Input 5 0 1 0 2 0 3 3 4 Output 2 Input 2 0 1 Output 1 Input 10 2 8 6 0 4 1 7 6 2 3 8 6 6 9 2 4 5 8 Output 3
instruction
0
101,892
13
203,784
"Correct Solution: ``` import sys readline = sys.stdin.readline from collections import Counter from random import randrange def parorder(Edge, p): N = len(Edge) par = [0]*N par[p] = -1 stack = [p] order = [] visited = set([p]) ast = stack.append apo = order.append while stack: vn = stack.pop() apo(vn) for vf in Edge[vn]: if vf in visited: continue visited.add(vf) par[vf] = vn ast(vf) return par, order def getcld(p): res = [[] for _ in range(len(p))] for i, v in enumerate(p[1:], 1): res[v].append(i) return res N = int(readline()) Edge = [[] for _ in range(N)] Leaf = [0]*N for _ in range(N-1): a, b = map(int, readline().split()) Leaf[a] += 1 Leaf[b] += 1 Edge[a].append(b) Edge[b].append(a) Leaf = [i for i in range(N) if Leaf[i] == 1] M = len(Leaf) ANS = 10**9+7 for idx in [0] + [randrange(1, M) for _ in range(10)]: root = Leaf[idx] P, L = parorder(Edge, root) C = getcld(P) dp = [0]*N countone = [0]*N for l in L[::-1][:-1]: p = P[l] dp[l] += 1 + max(0, countone[l] - 1) if dp[l] == 1: countone[p] += 1 dp[p] += dp[l] - 1 dp[root] += 1 + max(0, countone[root] - 1) ANS = min(ANS, dp[root]) print(ANS) ```
output
1
101,892
13
203,785
Provide a correct Python 3 solution for this coding contest problem. We have a tree with N vertices. The vertices are numbered 0 through N - 1, and the i-th edge (0 ≤ i < N - 1) comnnects Vertex a_i and b_i. For each pair of vertices u and v (0 ≤ u, v < N), we define the distance d(u, v) as the number of edges in the path u-v. It is expected that one of the vertices will be invaded by aliens from outer space. Snuke wants to immediately identify that vertex when the invasion happens. To do so, he has decided to install an antenna on some vertices. First, he decides the number of antennas, K (1 ≤ K ≤ N). Then, he chooses K different vertices, x_0, x_1, ..., x_{K - 1}, on which he installs Antenna 0, 1, ..., K - 1, respectively. If Vertex v is invaded by aliens, Antenna k (0 ≤ k < K) will output the distance d(x_k, v). Based on these K outputs, Snuke will identify the vertex that is invaded. Thus, in order to identify the invaded vertex no matter which one is invaded, the following condition must hold: * For each vertex u (0 ≤ u < N), consider the vector (d(x_0, u), ..., d(x_{K - 1}, u)). These N vectors are distinct. Find the minumum value of K, the number of antennas, when the condition is satisfied. Constraints * 2 ≤ N ≤ 10^5 * 0 ≤ a_i, b_i < N * The given graph is a tree. Input Input is given from Standard Input in the following format: N a_0 b_0 a_1 b_1 : a_{N - 2} b_{N - 2} Output Print the minumum value of K, the number of antennas, when the condition is satisfied. Examples Input 5 0 1 0 2 0 3 3 4 Output 2 Input 2 0 1 Output 1 Input 10 2 8 6 0 4 1 7 6 2 3 8 6 6 9 2 4 5 8 Output 3
instruction
0
101,893
13
203,786
"Correct Solution: ``` """ Writer: SPD_9X2 https://atcoder.jp/contests/apc001/tasks/apc001_e 厳密な照明は難しいが… 直径を取る 直径の端点からbfs 全ての頂点に関して、部分木に少なくとも一つのアンテナを持つかのフラグを管理 子の数をkとする。その内x個がtrueの場合、k-1-x個のアンテナを追加。自分のflagをtrueにする 子がfalseで、子が0 or 1つしかない場合のみfalse継続 簡単な木では最適になることを実験したがどうだろうか…? """ import sys sys.setrecursionlimit(3*10**5) from collections import deque def NC_Dij(lis,start): ret = [float("inf")] * len(lis) ret[start] = 0 q = deque([start]) plis = [i for i in range(len(lis))] while len(q) > 0: now = q.popleft() for nex in lis[now]: if ret[nex] > ret[now] + 1: ret[nex] = ret[now] + 1 plis[nex] = now q.append(nex) return ret,plis,now N = int(input()) lis = [ [] for i in range(N) ] for i in range(N-1): a,b = map(int,input().split()) lis[a].append(b) lis[b].append(a) td,tp,stp = NC_Dij(lis,0) ans = 0 def dfs(v,p): x = 0 c = 0 retflag = False for nex in lis[v]: if nex != p: c += 1 have = dfs(nex,v) retflag = have or retflag if have: x += 1 if c-1-x > 0: retflag = True global ans ans += max(0,c-1-x) return retflag dfs(stp,stp) print (ans+1) ```
output
1
101,893
13
203,787
Provide a correct Python 3 solution for this coding contest problem. We have a tree with N vertices. The vertices are numbered 0 through N - 1, and the i-th edge (0 ≤ i < N - 1) comnnects Vertex a_i and b_i. For each pair of vertices u and v (0 ≤ u, v < N), we define the distance d(u, v) as the number of edges in the path u-v. It is expected that one of the vertices will be invaded by aliens from outer space. Snuke wants to immediately identify that vertex when the invasion happens. To do so, he has decided to install an antenna on some vertices. First, he decides the number of antennas, K (1 ≤ K ≤ N). Then, he chooses K different vertices, x_0, x_1, ..., x_{K - 1}, on which he installs Antenna 0, 1, ..., K - 1, respectively. If Vertex v is invaded by aliens, Antenna k (0 ≤ k < K) will output the distance d(x_k, v). Based on these K outputs, Snuke will identify the vertex that is invaded. Thus, in order to identify the invaded vertex no matter which one is invaded, the following condition must hold: * For each vertex u (0 ≤ u < N), consider the vector (d(x_0, u), ..., d(x_{K - 1}, u)). These N vectors are distinct. Find the minumum value of K, the number of antennas, when the condition is satisfied. Constraints * 2 ≤ N ≤ 10^5 * 0 ≤ a_i, b_i < N * The given graph is a tree. Input Input is given from Standard Input in the following format: N a_0 b_0 a_1 b_1 : a_{N - 2} b_{N - 2} Output Print the minumum value of K, the number of antennas, when the condition is satisfied. Examples Input 5 0 1 0 2 0 3 3 4 Output 2 Input 2 0 1 Output 1 Input 10 2 8 6 0 4 1 7 6 2 3 8 6 6 9 2 4 5 8 Output 3
instruction
0
101,894
13
203,788
"Correct Solution: ``` from collections import defaultdict, deque, Counter from heapq import heappush, heappop, heapify import math from bisect import bisect_left, bisect_right import random from itertools import permutations, accumulate, combinations import sys import string from copy import deepcopy INF = 10 ** 20 sys.setrecursionlimit(2147483647) def LI(): return list(map(int, sys.stdin.readline().split())) def I(): return int(sys.stdin.readline()) def LS(): return sys.stdin.readline().split() def S(): return sys.stdin.readline().strip() def IR(n): return [I() for i in range(n)] def LIR(n): return [LI() for i in range(n)] def SR(n): return [S() for i in range(n)] def LSR(n): return [LS() for i in range(n)] def SRL(n): return [list(S()) for i in range(n)] def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)] mod = 10 ** 9 + 7 n=I() G=[[]for _ in range(n)] r=-1 for _ in range(n-1): a,b=LI() G[a]+=[b] G[b]+=[a] if len(G[a])>2: r=a if len(G[b]) > 2: r=b visited=[0]*n visited[r]=1 def f(x): ret=0 cnt=0 for v in G[x]: if visited[v]: continue visited[v] = 1 r=f(v) ret+=r if r==0: cnt+=1 if cnt>1: ret+=cnt-1 return ret print(1 if r == -1 else f(r)) ```
output
1
101,894
13
203,789
Provide a correct Python 3 solution for this coding contest problem. We have a tree with N vertices. The vertices are numbered 0 through N - 1, and the i-th edge (0 ≤ i < N - 1) comnnects Vertex a_i and b_i. For each pair of vertices u and v (0 ≤ u, v < N), we define the distance d(u, v) as the number of edges in the path u-v. It is expected that one of the vertices will be invaded by aliens from outer space. Snuke wants to immediately identify that vertex when the invasion happens. To do so, he has decided to install an antenna on some vertices. First, he decides the number of antennas, K (1 ≤ K ≤ N). Then, he chooses K different vertices, x_0, x_1, ..., x_{K - 1}, on which he installs Antenna 0, 1, ..., K - 1, respectively. If Vertex v is invaded by aliens, Antenna k (0 ≤ k < K) will output the distance d(x_k, v). Based on these K outputs, Snuke will identify the vertex that is invaded. Thus, in order to identify the invaded vertex no matter which one is invaded, the following condition must hold: * For each vertex u (0 ≤ u < N), consider the vector (d(x_0, u), ..., d(x_{K - 1}, u)). These N vectors are distinct. Find the minumum value of K, the number of antennas, when the condition is satisfied. Constraints * 2 ≤ N ≤ 10^5 * 0 ≤ a_i, b_i < N * The given graph is a tree. Input Input is given from Standard Input in the following format: N a_0 b_0 a_1 b_1 : a_{N - 2} b_{N - 2} Output Print the minumum value of K, the number of antennas, when the condition is satisfied. Examples Input 5 0 1 0 2 0 3 3 4 Output 2 Input 2 0 1 Output 1 Input 10 2 8 6 0 4 1 7 6 2 3 8 6 6 9 2 4 5 8 Output 3
instruction
0
101,895
13
203,790
"Correct Solution: ``` #設定 import sys input = sys.stdin.buffer.readline sys.setrecursionlimit(10**7) #ライブラリインポート from collections import defaultdict #入力受け取り def getlist(): return list(map(int, input().split())) class Graph(object): def __init__(self): self.graph = defaultdict(list) def __len__(self): return len(self.graph) def add_edge(self, a, b): self.graph[a].append(b) def get_nodes(self): return self.graph.keys() #val = 0 def DFS(G, anstenna, edge_num, have, visit, node): cnt = 0 for i in G.graph[node]: if visit[i] != "Yes": visit[i] = "Yes" DFS(G, anstenna, edge_num, have, visit, i) if have[i] == 1: cnt += 1 anstenna[node] += anstenna[i] if cnt < edge_num[node] - 1: anstenna[node] += edge_num[node] - 1 - cnt if anstenna[node] >= 1: have[node] = 1 #処理内容 def main(): N = int(input()) G = Graph() for i in range(N - 1): a, b = getlist() G.add_edge(a, b) G.add_edge(b, a) if N == 2: print(1) return #DFS anstenna = [0] * (N + 1) have = [0] * (N + 1) edge_num = [len(G.graph[i]) - 1 for i in range(N + 1)] if max(edge_num) <= 1: print(1) return visit = ["No"] * (N + 1) visit[N] = "Yes" s = None for i in range(N): if edge_num[i] >= 1: s = i break G.add_edge(N, s) G.add_edge(s, N) edge_num[s] += 1 DFS(G, anstenna, edge_num, have, visit, N) ans = anstenna[N] if edge_num[s] == 2: cnt = 0 for i in G.graph[s]: if have[i] == 1: cnt += 1 if cnt <= 2: ans += 1 print(ans) if __name__ == '__main__': main() ```
output
1
101,895
13
203,791
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. We have a tree with N vertices. The vertices are numbered 0 through N - 1, and the i-th edge (0 ≤ i < N - 1) comnnects Vertex a_i and b_i. For each pair of vertices u and v (0 ≤ u, v < N), we define the distance d(u, v) as the number of edges in the path u-v. It is expected that one of the vertices will be invaded by aliens from outer space. Snuke wants to immediately identify that vertex when the invasion happens. To do so, he has decided to install an antenna on some vertices. First, he decides the number of antennas, K (1 ≤ K ≤ N). Then, he chooses K different vertices, x_0, x_1, ..., x_{K - 1}, on which he installs Antenna 0, 1, ..., K - 1, respectively. If Vertex v is invaded by aliens, Antenna k (0 ≤ k < K) will output the distance d(x_k, v). Based on these K outputs, Snuke will identify the vertex that is invaded. Thus, in order to identify the invaded vertex no matter which one is invaded, the following condition must hold: * For each vertex u (0 ≤ u < N), consider the vector (d(x_0, u), ..., d(x_{K - 1}, u)). These N vectors are distinct. Find the minumum value of K, the number of antennas, when the condition is satisfied. Constraints * 2 ≤ N ≤ 10^5 * 0 ≤ a_i, b_i < N * The given graph is a tree. Input Input is given from Standard Input in the following format: N a_0 b_0 a_1 b_1 : a_{N - 2} b_{N - 2} Output Print the minumum value of K, the number of antennas, when the condition is satisfied. Examples Input 5 0 1 0 2 0 3 3 4 Output 2 Input 2 0 1 Output 1 Input 10 2 8 6 0 4 1 7 6 2 3 8 6 6 9 2 4 5 8 Output 3 Submitted Solution: ``` n = int(input()) g = [[] for _ in range(n)] for i in range(n-1): a,b = map(int,input().split()) g[a].append(b) g[b].append(a) ones = list(filter(lambda i:len(g[i])==1,range(n))) if max([len(g[i]) for i in range(n)]) <= 2: print(1) exit() def nbh(i): inext = g[i][0] def nbh_(xnext,x): return g[xnext][0] ^ g[xnext][1] ^ x while len(g[inext]) <= 2: i,inext = inext,nbh_(inext,i) return inext edges = list(set([nbh(i) for i in ones])) print(len(ones)-len(edges)) ```
instruction
0
101,896
13
203,792
Yes
output
1
101,896
13
203,793
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. We have a tree with N vertices. The vertices are numbered 0 through N - 1, and the i-th edge (0 ≤ i < N - 1) comnnects Vertex a_i and b_i. For each pair of vertices u and v (0 ≤ u, v < N), we define the distance d(u, v) as the number of edges in the path u-v. It is expected that one of the vertices will be invaded by aliens from outer space. Snuke wants to immediately identify that vertex when the invasion happens. To do so, he has decided to install an antenna on some vertices. First, he decides the number of antennas, K (1 ≤ K ≤ N). Then, he chooses K different vertices, x_0, x_1, ..., x_{K - 1}, on which he installs Antenna 0, 1, ..., K - 1, respectively. If Vertex v is invaded by aliens, Antenna k (0 ≤ k < K) will output the distance d(x_k, v). Based on these K outputs, Snuke will identify the vertex that is invaded. Thus, in order to identify the invaded vertex no matter which one is invaded, the following condition must hold: * For each vertex u (0 ≤ u < N), consider the vector (d(x_0, u), ..., d(x_{K - 1}, u)). These N vectors are distinct. Find the minumum value of K, the number of antennas, when the condition is satisfied. Constraints * 2 ≤ N ≤ 10^5 * 0 ≤ a_i, b_i < N * The given graph is a tree. Input Input is given from Standard Input in the following format: N a_0 b_0 a_1 b_1 : a_{N - 2} b_{N - 2} Output Print the minumum value of K, the number of antennas, when the condition is satisfied. Examples Input 5 0 1 0 2 0 3 3 4 Output 2 Input 2 0 1 Output 1 Input 10 2 8 6 0 4 1 7 6 2 3 8 6 6 9 2 4 5 8 Output 3 Submitted Solution: ``` # 大混乱したので乱択 from random import randint def main(): import sys sys.setrecursionlimit(500000) N = int(input()) if N==2: print(1) exit() E = [[] for _ in range(N)] for _ in range(N-1): a, b = map(int, input().split()) E[a].append(b) E[b].append(a) def dfs(v=0, p=-1, root=0): cnt_child = 0 cnt_false = 0 res = 0 for u in E[v]: if u!=p: cnt_child += 1 d = dfs(u, v, root) res += d cnt_false += d == 0 return res + max(0, cnt_false - 1) #for i in range(N): # print(dfs(i, -1, i)) print(max(dfs(i, -1, i) for i in sorted(range(N), key=lambda x: -len(E[x]))[:5])) main() ```
instruction
0
101,897
13
203,794
Yes
output
1
101,897
13
203,795
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. We have a tree with N vertices. The vertices are numbered 0 through N - 1, and the i-th edge (0 ≤ i < N - 1) comnnects Vertex a_i and b_i. For each pair of vertices u and v (0 ≤ u, v < N), we define the distance d(u, v) as the number of edges in the path u-v. It is expected that one of the vertices will be invaded by aliens from outer space. Snuke wants to immediately identify that vertex when the invasion happens. To do so, he has decided to install an antenna on some vertices. First, he decides the number of antennas, K (1 ≤ K ≤ N). Then, he chooses K different vertices, x_0, x_1, ..., x_{K - 1}, on which he installs Antenna 0, 1, ..., K - 1, respectively. If Vertex v is invaded by aliens, Antenna k (0 ≤ k < K) will output the distance d(x_k, v). Based on these K outputs, Snuke will identify the vertex that is invaded. Thus, in order to identify the invaded vertex no matter which one is invaded, the following condition must hold: * For each vertex u (0 ≤ u < N), consider the vector (d(x_0, u), ..., d(x_{K - 1}, u)). These N vectors are distinct. Find the minumum value of K, the number of antennas, when the condition is satisfied. Constraints * 2 ≤ N ≤ 10^5 * 0 ≤ a_i, b_i < N * The given graph is a tree. Input Input is given from Standard Input in the following format: N a_0 b_0 a_1 b_1 : a_{N - 2} b_{N - 2} Output Print the minumum value of K, the number of antennas, when the condition is satisfied. Examples Input 5 0 1 0 2 0 3 3 4 Output 2 Input 2 0 1 Output 1 Input 10 2 8 6 0 4 1 7 6 2 3 8 6 6 9 2 4 5 8 Output 3 Submitted Solution: ``` import sys input = sys.stdin.readline sys.setrecursionlimit(10**6) N = int(input()) G = [[] for _ in range(N)] for _ in range(N-1): a, b = map(int, input().split()) G[a].append(b) G[b].append(a) dp = [1] * N def dfs(v, p): cnt = 0 for c in G[v]: if c == p: continue dfs(c, v) if dp[c] == 1: cnt += 1 dp[v] += dp[c] - 1 if cnt > 1: dp[v] += cnt - 1 dfs(0, -1) ans = [1] * N def dfs2(v, p, par_val): cnt = 0 for c in G[v]: if c == p: continue if dp[c] == 1: cnt += 1 ans[v] += dp[c] - 1 if p != -1: if par_val == 1: cnt += 1 ans[v] += par_val - 1 if cnt > 1: ans[v] += cnt - 1 for c in G[v]: if c == p: continue dfs2(c, v, ans[v] - (dp[c] - 1) - (1 if dp[c] == 1 and cnt > 1 else 0)) dfs2(0, -1, 0) print(min(ans)) ```
instruction
0
101,898
13
203,796
Yes
output
1
101,898
13
203,797
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. We have a tree with N vertices. The vertices are numbered 0 through N - 1, and the i-th edge (0 ≤ i < N - 1) comnnects Vertex a_i and b_i. For each pair of vertices u and v (0 ≤ u, v < N), we define the distance d(u, v) as the number of edges in the path u-v. It is expected that one of the vertices will be invaded by aliens from outer space. Snuke wants to immediately identify that vertex when the invasion happens. To do so, he has decided to install an antenna on some vertices. First, he decides the number of antennas, K (1 ≤ K ≤ N). Then, he chooses K different vertices, x_0, x_1, ..., x_{K - 1}, on which he installs Antenna 0, 1, ..., K - 1, respectively. If Vertex v is invaded by aliens, Antenna k (0 ≤ k < K) will output the distance d(x_k, v). Based on these K outputs, Snuke will identify the vertex that is invaded. Thus, in order to identify the invaded vertex no matter which one is invaded, the following condition must hold: * For each vertex u (0 ≤ u < N), consider the vector (d(x_0, u), ..., d(x_{K - 1}, u)). These N vectors are distinct. Find the minumum value of K, the number of antennas, when the condition is satisfied. Constraints * 2 ≤ N ≤ 10^5 * 0 ≤ a_i, b_i < N * The given graph is a tree. Input Input is given from Standard Input in the following format: N a_0 b_0 a_1 b_1 : a_{N - 2} b_{N - 2} Output Print the minumum value of K, the number of antennas, when the condition is satisfied. Examples Input 5 0 1 0 2 0 3 3 4 Output 2 Input 2 0 1 Output 1 Input 10 2 8 6 0 4 1 7 6 2 3 8 6 6 9 2 4 5 8 Output 3 Submitted Solution: ``` import sys input = sys.stdin.readline N = int(input()) adj = [[] for _ in range(N)] for _ in range(N - 1): a, b = map(int, input().split()) adj[a].append(b) adj[b].append(a) leaf = [] for i in range(N): if len(adj[i]) == 1: leaf.append(i) if len(leaf) == 2: print(1) sys.exit() par = {} for v in leaf: while True: v_list = adj[v] if len(v_list) == 1: v_prev = v v = v_list[0] else: v1, v2 = v_list v, v_prev = v1 + v2 - v_prev, v if len(adj[v]) > 2: par[v] = 0 break print(len(leaf) - len(par)) ```
instruction
0
101,899
13
203,798
Yes
output
1
101,899
13
203,799
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. We have a tree with N vertices. The vertices are numbered 0 through N - 1, and the i-th edge (0 ≤ i < N - 1) comnnects Vertex a_i and b_i. For each pair of vertices u and v (0 ≤ u, v < N), we define the distance d(u, v) as the number of edges in the path u-v. It is expected that one of the vertices will be invaded by aliens from outer space. Snuke wants to immediately identify that vertex when the invasion happens. To do so, he has decided to install an antenna on some vertices. First, he decides the number of antennas, K (1 ≤ K ≤ N). Then, he chooses K different vertices, x_0, x_1, ..., x_{K - 1}, on which he installs Antenna 0, 1, ..., K - 1, respectively. If Vertex v is invaded by aliens, Antenna k (0 ≤ k < K) will output the distance d(x_k, v). Based on these K outputs, Snuke will identify the vertex that is invaded. Thus, in order to identify the invaded vertex no matter which one is invaded, the following condition must hold: * For each vertex u (0 ≤ u < N), consider the vector (d(x_0, u), ..., d(x_{K - 1}, u)). These N vectors are distinct. Find the minumum value of K, the number of antennas, when the condition is satisfied. Constraints * 2 ≤ N ≤ 10^5 * 0 ≤ a_i, b_i < N * The given graph is a tree. Input Input is given from Standard Input in the following format: N a_0 b_0 a_1 b_1 : a_{N - 2} b_{N - 2} Output Print the minumum value of K, the number of antennas, when the condition is satisfied. Examples Input 5 0 1 0 2 0 3 3 4 Output 2 Input 2 0 1 Output 1 Input 10 2 8 6 0 4 1 7 6 2 3 8 6 6 9 2 4 5 8 Output 3 Submitted Solution: ``` import sys input = sys.stdin.readline sys.setrecursionlimit(10**6) N = int(input()) graph = [[] for _ in range(N+1)] for _ in range(N-1): a, b = map(int, input().split()) graph[a].append(b) graph[b].append(a) s = -1 for n in range(N): if len(graph[n]) > 1: s = n break checked = [False]*N def dfs(p, ans): checked[p] = True s = 0 t = 0 for np in graph[p]: if not checked[np]: exists, ans = dfs(np, ans) t += 1 if exists: s += 1 if t <= 1: return (s>0), ans if s == t: return True, ans ans += (t-s)-1 return True, ans def dfs2(s): ans = 0 S = [0]*N T = [0]*N stack = [s] while stack: p = stack[-1] checked[p] = True for np in graph[p]: if not checked[np]: stack.append(np) break if stack[-1] != p: continue ans += max(T[p] - S[p] - 1, 0) stack.pop() if stack: par = stack[-1] T[par] += 1 if S[p] > 0 or T[p] > 1: S[par] += 1 return ans if s == -1: ans = 1 else: #_, ans = dfs(s, 0) ans = dfs2(s) print(ans) ```
instruction
0
101,900
13
203,800
No
output
1
101,900
13
203,801
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. We have a tree with N vertices. The vertices are numbered 0 through N - 1, and the i-th edge (0 ≤ i < N - 1) comnnects Vertex a_i and b_i. For each pair of vertices u and v (0 ≤ u, v < N), we define the distance d(u, v) as the number of edges in the path u-v. It is expected that one of the vertices will be invaded by aliens from outer space. Snuke wants to immediately identify that vertex when the invasion happens. To do so, he has decided to install an antenna on some vertices. First, he decides the number of antennas, K (1 ≤ K ≤ N). Then, he chooses K different vertices, x_0, x_1, ..., x_{K - 1}, on which he installs Antenna 0, 1, ..., K - 1, respectively. If Vertex v is invaded by aliens, Antenna k (0 ≤ k < K) will output the distance d(x_k, v). Based on these K outputs, Snuke will identify the vertex that is invaded. Thus, in order to identify the invaded vertex no matter which one is invaded, the following condition must hold: * For each vertex u (0 ≤ u < N), consider the vector (d(x_0, u), ..., d(x_{K - 1}, u)). These N vectors are distinct. Find the minumum value of K, the number of antennas, when the condition is satisfied. Constraints * 2 ≤ N ≤ 10^5 * 0 ≤ a_i, b_i < N * The given graph is a tree. Input Input is given from Standard Input in the following format: N a_0 b_0 a_1 b_1 : a_{N - 2} b_{N - 2} Output Print the minumum value of K, the number of antennas, when the condition is satisfied. Examples Input 5 0 1 0 2 0 3 3 4 Output 2 Input 2 0 1 Output 1 Input 10 2 8 6 0 4 1 7 6 2 3 8 6 6 9 2 4 5 8 Output 3 Submitted Solution: ``` import sys readline = sys.stdin.readline from collections import Counter def parorder(Edge, p): N = len(Edge) par = [0]*N par[p] = -1 stack = [p] order = [] visited = set([p]) ast = stack.append apo = order.append while stack: vn = stack.pop() apo(vn) for vf in Edge[vn]: if vf in visited: continue visited.add(vf) par[vf] = vn ast(vf) return par, order def getcld(p): res = [[] for _ in range(len(p))] for i, v in enumerate(p[1:], 1): res[v].append(i) return res N = int(readline()) Edge = [[] for _ in range(N)] Leaf = [0]*N for _ in range(N-1): a, b = map(int, readline().split()) Leaf[a] += 1 Leaf[b] += 1 Edge[a].append(b) Edge[b].append(a) root = Leaf.index(1) P, L = parorder(Edge, root) C = getcld(P) dp = [0]*N countone = [0]*N for l in L[::-1][:-1]: p = P[l] dp[l] += 1 + max(0, countone[l] - 1) if dp[l] == 1: countone[p] += 1 dp[p] += dp[l] - 1 dp[root] += 1 + max(0, countone[0] - 1) print(dp[0]) ```
instruction
0
101,901
13
203,802
No
output
1
101,901
13
203,803
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. We have a tree with N vertices. The vertices are numbered 0 through N - 1, and the i-th edge (0 ≤ i < N - 1) comnnects Vertex a_i and b_i. For each pair of vertices u and v (0 ≤ u, v < N), we define the distance d(u, v) as the number of edges in the path u-v. It is expected that one of the vertices will be invaded by aliens from outer space. Snuke wants to immediately identify that vertex when the invasion happens. To do so, he has decided to install an antenna on some vertices. First, he decides the number of antennas, K (1 ≤ K ≤ N). Then, he chooses K different vertices, x_0, x_1, ..., x_{K - 1}, on which he installs Antenna 0, 1, ..., K - 1, respectively. If Vertex v is invaded by aliens, Antenna k (0 ≤ k < K) will output the distance d(x_k, v). Based on these K outputs, Snuke will identify the vertex that is invaded. Thus, in order to identify the invaded vertex no matter which one is invaded, the following condition must hold: * For each vertex u (0 ≤ u < N), consider the vector (d(x_0, u), ..., d(x_{K - 1}, u)). These N vectors are distinct. Find the minumum value of K, the number of antennas, when the condition is satisfied. Constraints * 2 ≤ N ≤ 10^5 * 0 ≤ a_i, b_i < N * The given graph is a tree. Input Input is given from Standard Input in the following format: N a_0 b_0 a_1 b_1 : a_{N - 2} b_{N - 2} Output Print the minumum value of K, the number of antennas, when the condition is satisfied. Examples Input 5 0 1 0 2 0 3 3 4 Output 2 Input 2 0 1 Output 1 Input 10 2 8 6 0 4 1 7 6 2 3 8 6 6 9 2 4 5 8 Output 3 Submitted Solution: ``` """ Writer: SPD_9X2 https://atcoder.jp/contests/apc001/tasks/apc001_e 厳密な照明は難しいが… 直径を取る 直径の端点からbfs 全ての頂点に関して、部分木に少なくとも一つのアンテナを持つかのフラグを管理 子の数をkとする。その内x個がtrueの場合、k-1-x個のアンテナを追加。自分のflagをtrueにする 子がfalseで、子が0 or 1つしかない場合のみfalse継続 簡単な木では最適になることを実験したがどうだろうか…? """ from collections import deque def NC_Dij(lis,start): ret = [float("inf")] * len(lis) ret[start] = 0 q = deque([start]) plis = [i for i in range(len(lis))] while len(q) > 0: now = q.popleft() for nex in lis[now]: if ret[nex] > ret[now] + 1: ret[nex] = ret[now] + 1 plis[nex] = now q.append(nex) return ret,plis,now N = int(input()) lis = [ [] for i in range(N) ] for i in range(N-1): a,b = map(int,input().split()) lis[a].append(b) lis[b].append(a) td,tp,stp = NC_Dij(lis,0) ans = 0 def dfs(v,p): x = 0 c = 0 retflag = False for nex in lis[v]: if nex != p: c += 1 have = dfs(nex,v) retflag = have or retflag if have: x += 1 if c-1-x > 0: retflag = True global ans ans += max(0,c-1-x) return retflag dfs(stp,stp) print (ans+1) ```
instruction
0
101,902
13
203,804
No
output
1
101,902
13
203,805
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. We have a tree with N vertices. The vertices are numbered 0 through N - 1, and the i-th edge (0 ≤ i < N - 1) comnnects Vertex a_i and b_i. For each pair of vertices u and v (0 ≤ u, v < N), we define the distance d(u, v) as the number of edges in the path u-v. It is expected that one of the vertices will be invaded by aliens from outer space. Snuke wants to immediately identify that vertex when the invasion happens. To do so, he has decided to install an antenna on some vertices. First, he decides the number of antennas, K (1 ≤ K ≤ N). Then, he chooses K different vertices, x_0, x_1, ..., x_{K - 1}, on which he installs Antenna 0, 1, ..., K - 1, respectively. If Vertex v is invaded by aliens, Antenna k (0 ≤ k < K) will output the distance d(x_k, v). Based on these K outputs, Snuke will identify the vertex that is invaded. Thus, in order to identify the invaded vertex no matter which one is invaded, the following condition must hold: * For each vertex u (0 ≤ u < N), consider the vector (d(x_0, u), ..., d(x_{K - 1}, u)). These N vectors are distinct. Find the minumum value of K, the number of antennas, when the condition is satisfied. Constraints * 2 ≤ N ≤ 10^5 * 0 ≤ a_i, b_i < N * The given graph is a tree. Input Input is given from Standard Input in the following format: N a_0 b_0 a_1 b_1 : a_{N - 2} b_{N - 2} Output Print the minumum value of K, the number of antennas, when the condition is satisfied. Examples Input 5 0 1 0 2 0 3 3 4 Output 2 Input 2 0 1 Output 1 Input 10 2 8 6 0 4 1 7 6 2 3 8 6 6 9 2 4 5 8 Output 3 Submitted Solution: ``` def dps(v, p, links): lv = links[v] if not lv: return 0 cnt0 = 0 ret = 0 for l in lv: if l == p: continue res = dps(l, v, links) ret += res if res == 0: cnt0 += 1 if cnt0: ret += cnt0 - 1 return ret def solve(n, links): if n == 2: return 1 for i, l in enumerate(links): if len(l) > 1: return dps(i, None, links) n = int(input()) links = [set() for _ in range(n)] for _ in range(n - 1): a, b = map(int, input().split()) links[a].add(b) links[b].add(a) print(solve(n, links)) ```
instruction
0
101,903
13
203,806
No
output
1
101,903
13
203,807
Provide tags and a correct Python 3 solution for this coding contest problem. Ivan is developing his own computer game. Now he tries to create some levels for his game. But firstly for each level he needs to draw a graph representing the structure of the level. Ivan decided that there should be exactly ni vertices in the graph representing level i, and the edges have to be bidirectional. When constructing the graph, Ivan is interested in special edges called bridges. An edge between two vertices u and v is called a bridge if this edge belongs to every path between u and v (and these vertices will belong to different connected components if we delete this edge). For each level Ivan wants to construct a graph where at least half of the edges are bridges. He also wants to maximize the number of edges in each constructed graph. So the task Ivan gave you is: given q numbers n1, n2, ..., nq, for each i tell the maximum number of edges in a graph with ni vertices, if at least half of the edges are bridges. Note that the graphs cannot contain multiple edges or self-loops. Input The first line of input file contains a positive integer q (1 ≤ q ≤ 100 000) — the number of graphs Ivan needs to construct. Then q lines follow, i-th line contains one positive integer ni (1 ≤ ni ≤ 2·109) — the number of vertices in i-th graph. Note that in hacks you have to use q = 1. Output Output q numbers, i-th of them must be equal to the maximum number of edges in i-th graph. Example Input 3 3 4 6 Output 2 3 6 Note In the first example it is possible to construct these graphs: 1. 1 - 2, 1 - 3; 2. 1 - 2, 1 - 3, 2 - 4; 3. 1 - 2, 1 - 3, 2 - 3, 1 - 4, 2 - 5, 3 - 6.
instruction
0
102,582
13
205,164
Tags: binary search, math, ternary search Correct Solution: ``` #! /usr/bin/env python # http://codeforces.com/problemset/problem/818/F # Problem name ::: F. Level Generation # submission number #212055293 #508427854 def newest_approach(n): from math import floor, ceil, sqrt quad_solv = sqrt(2*n+1/4)-1/2 x = floor(quad_solv) y = ceil(quad_solv) xed = int(x*(x-1)/2 + n - x) xbr = n - x ybr = n - y yed = 2*ybr if xed > yed: print(xed) # print("nodes = %s :: edges = %s :: bridges = %s" % (n, xed, xbr)) else: print(yed) # print("nodes = %s :: edges = %s :: bridges = %s" % (n, yed, ybr)) return def main(): import sys data = [line.rstrip() for line in sys.stdin.readlines()] num_graphs = data[0] graph_sizes = [int(x) for x in data[1:]] for val in graph_sizes: # binary_search(val) # new_approach(val) newest_approach(val) if __name__ == '__main__': main() ```
output
1
102,582
13
205,165
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Ivan is developing his own computer game. Now he tries to create some levels for his game. But firstly for each level he needs to draw a graph representing the structure of the level. Ivan decided that there should be exactly ni vertices in the graph representing level i, and the edges have to be bidirectional. When constructing the graph, Ivan is interested in special edges called bridges. An edge between two vertices u and v is called a bridge if this edge belongs to every path between u and v (and these vertices will belong to different connected components if we delete this edge). For each level Ivan wants to construct a graph where at least half of the edges are bridges. He also wants to maximize the number of edges in each constructed graph. So the task Ivan gave you is: given q numbers n1, n2, ..., nq, for each i tell the maximum number of edges in a graph with ni vertices, if at least half of the edges are bridges. Note that the graphs cannot contain multiple edges or self-loops. Input The first line of input file contains a positive integer q (1 ≤ q ≤ 100 000) — the number of graphs Ivan needs to construct. Then q lines follow, i-th line contains one positive integer ni (1 ≤ ni ≤ 2·109) — the number of vertices in i-th graph. Note that in hacks you have to use q = 1. Output Output q numbers, i-th of them must be equal to the maximum number of edges in i-th graph. Example Input 3 3 4 6 Output 2 3 6 Note In the first example it is possible to construct these graphs: 1. 1 - 2, 1 - 3; 2. 1 - 2, 1 - 3, 2 - 4; 3. 1 - 2, 1 - 3, 2 - 3, 1 - 4, 2 - 5, 3 - 6. Submitted Solution: ``` n = int(input()) def solve(n): if n == 1: return 0 if n == 2: return 1 def f(k): return k + (n - k) * (n - k - 1) // 2 lower = max(n // 2 + n % 2, (2 * n - 3) // 2 - 2) upper = min(lower + 3, n - 1) think = range(lower, upper + 1) ans = think[0] for x in think: if f(ans) < f(x): ans = x return f(ans) while n: n -= 1 print(solve(int(input()))) ```
instruction
0
102,583
13
205,166
No
output
1
102,583
13
205,167
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Ivan is developing his own computer game. Now he tries to create some levels for his game. But firstly for each level he needs to draw a graph representing the structure of the level. Ivan decided that there should be exactly ni vertices in the graph representing level i, and the edges have to be bidirectional. When constructing the graph, Ivan is interested in special edges called bridges. An edge between two vertices u and v is called a bridge if this edge belongs to every path between u and v (and these vertices will belong to different connected components if we delete this edge). For each level Ivan wants to construct a graph where at least half of the edges are bridges. He also wants to maximize the number of edges in each constructed graph. So the task Ivan gave you is: given q numbers n1, n2, ..., nq, for each i tell the maximum number of edges in a graph with ni vertices, if at least half of the edges are bridges. Note that the graphs cannot contain multiple edges or self-loops. Input The first line of input file contains a positive integer q (1 ≤ q ≤ 100 000) — the number of graphs Ivan needs to construct. Then q lines follow, i-th line contains one positive integer ni (1 ≤ ni ≤ 2·109) — the number of vertices in i-th graph. Note that in hacks you have to use q = 1. Output Output q numbers, i-th of them must be equal to the maximum number of edges in i-th graph. Example Input 3 3 4 6 Output 2 3 6 Note In the first example it is possible to construct these graphs: 1. 1 - 2, 1 - 3; 2. 1 - 2, 1 - 3, 2 - 4; 3. 1 - 2, 1 - 3, 2 - 3, 1 - 4, 2 - 5, 3 - 6. Submitted Solution: ``` import math q = int(input()) for i in range(q): n = int(input()) x = int(math.sqrt(2 * n)) t = x * (x - 1) // 2 print(n - x + min(max(n - x, 1), t)) ```
instruction
0
102,584
13
205,168
No
output
1
102,584
13
205,169
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Ivan is developing his own computer game. Now he tries to create some levels for his game. But firstly for each level he needs to draw a graph representing the structure of the level. Ivan decided that there should be exactly ni vertices in the graph representing level i, and the edges have to be bidirectional. When constructing the graph, Ivan is interested in special edges called bridges. An edge between two vertices u and v is called a bridge if this edge belongs to every path between u and v (and these vertices will belong to different connected components if we delete this edge). For each level Ivan wants to construct a graph where at least half of the edges are bridges. He also wants to maximize the number of edges in each constructed graph. So the task Ivan gave you is: given q numbers n1, n2, ..., nq, for each i tell the maximum number of edges in a graph with ni vertices, if at least half of the edges are bridges. Note that the graphs cannot contain multiple edges or self-loops. Input The first line of input file contains a positive integer q (1 ≤ q ≤ 100 000) — the number of graphs Ivan needs to construct. Then q lines follow, i-th line contains one positive integer ni (1 ≤ ni ≤ 2·109) — the number of vertices in i-th graph. Note that in hacks you have to use q = 1. Output Output q numbers, i-th of them must be equal to the maximum number of edges in i-th graph. Example Input 3 3 4 6 Output 2 3 6 Note In the first example it is possible to construct these graphs: 1. 1 - 2, 1 - 3; 2. 1 - 2, 1 - 3, 2 - 4; 3. 1 - 2, 1 - 3, 2 - 3, 1 - 4, 2 - 5, 3 - 6. Submitted Solution: ``` q = int(input()) for i in range(q): n = int(input()) x = (n - 3) // 3 print(n - 1 + x) ```
instruction
0
102,585
13
205,170
No
output
1
102,585
13
205,171
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Ivan is developing his own computer game. Now he tries to create some levels for his game. But firstly for each level he needs to draw a graph representing the structure of the level. Ivan decided that there should be exactly ni vertices in the graph representing level i, and the edges have to be bidirectional. When constructing the graph, Ivan is interested in special edges called bridges. An edge between two vertices u and v is called a bridge if this edge belongs to every path between u and v (and these vertices will belong to different connected components if we delete this edge). For each level Ivan wants to construct a graph where at least half of the edges are bridges. He also wants to maximize the number of edges in each constructed graph. So the task Ivan gave you is: given q numbers n1, n2, ..., nq, for each i tell the maximum number of edges in a graph with ni vertices, if at least half of the edges are bridges. Note that the graphs cannot contain multiple edges or self-loops. Input The first line of input file contains a positive integer q (1 ≤ q ≤ 100 000) — the number of graphs Ivan needs to construct. Then q lines follow, i-th line contains one positive integer ni (1 ≤ ni ≤ 2·109) — the number of vertices in i-th graph. Note that in hacks you have to use q = 1. Output Output q numbers, i-th of them must be equal to the maximum number of edges in i-th graph. Example Input 3 3 4 6 Output 2 3 6 Note In the first example it is possible to construct these graphs: 1. 1 - 2, 1 - 3; 2. 1 - 2, 1 - 3, 2 - 4; 3. 1 - 2, 1 - 3, 2 - 3, 1 - 4, 2 - 5, 3 - 6. Submitted Solution: ``` #! /usr/bin/env python # http://codeforces.com/problemset/problem/818/F # Problem name ::: F. Level Generation # submission number def max_conn_comp(nodes, edges): for i in range(1, nodes+1): if i*(i-1)/2 >= edges: return nodes - i + 1 def binary_search(nodes): from math import ceil min_edges = 0 # maximum of "non-bridge" edges cannot excede nodes max_edges = nodes search_term = ceil((max_edges+min_edges)/2) count = 0 while True: # print(nodes, search_term) ccs = max_conn_comp(nodes, search_term) bridges = ccs - 1 if bridges < search_term: # print(bridges, search_term) max_edges = search_term search_term = ceil(search_term/2) elif bridges > search_term: # print(bridges, search_term) min_edges = search_term search_term = ceil((max_edges+search_term)/2) else: max_edges = bridges + search_term # print("max_edges_found = %s" % max_edges) # print("max_bridges_found = %s" % bridges) return max_edges count += 1 if count > max_edges: print("not found") break def main(): import sys data = [line.rstrip() for line in sys.stdin.readlines()] num_graphs = data[0] graph_sizes = [int(x) for x in data[1:]] for val in graph_sizes: # print(binary_search(val)) print(binary_search(val)) if __name__ == '__main__': main() ```
instruction
0
102,586
13
205,172
No
output
1
102,586
13
205,173
Provide tags and a correct Python 3 solution for this coding contest problem. Consider a rooted tree. A rooted tree has one special vertex called the root. All edges are directed from the root. Vertex u is called a child of vertex v and vertex v is called a parent of vertex u if there exists a directed edge from v to u. A vertex is called a leaf if it doesn't have children and has a parent. Let's call a rooted tree a spruce if its every non-leaf vertex has at least 3 leaf children. You are given a rooted tree, check whether it's a spruce. The definition of a rooted tree can be found [here](https://goo.gl/1dqvzz). Input The first line contains one integer n — the number of vertices in the tree (3 ≤ n ≤ 1 000). Each of the next n - 1 lines contains one integer pi (1 ≤ i ≤ n - 1) — the index of the parent of the i + 1-th vertex (1 ≤ pi ≤ i). Vertex 1 is the root. It's guaranteed that the root has at least 2 children. Output Print "Yes" if the tree is a spruce and "No" otherwise. Examples Input 4 1 1 1 Output Yes Input 7 1 1 1 2 2 2 Output No Input 8 1 1 1 1 3 3 3 Output Yes Note The first example: <image> The second example: <image> It is not a spruce, because the non-leaf vertex 1 has only 2 leaf children. The third example: <image>
instruction
0
102,625
13
205,250
Tags: implementation, trees Correct Solution: ``` n = int(input()) tree = {} for i in range(n-1): parent = int(input()) tree[parent] = tree.get(parent, []) + [i+2] def check_vertices(): for vertex in tree.keys(): leaf_cnt = 0 if len(tree[vertex]) >= 3: for child in tree[vertex]: if child not in set(tree.keys()): leaf_cnt += 1 if leaf_cnt < 3: return "NO" else: return "NO" return "YES" print(check_vertices()) ```
output
1
102,625
13
205,251
Provide tags and a correct Python 3 solution for this coding contest problem. Consider a rooted tree. A rooted tree has one special vertex called the root. All edges are directed from the root. Vertex u is called a child of vertex v and vertex v is called a parent of vertex u if there exists a directed edge from v to u. A vertex is called a leaf if it doesn't have children and has a parent. Let's call a rooted tree a spruce if its every non-leaf vertex has at least 3 leaf children. You are given a rooted tree, check whether it's a spruce. The definition of a rooted tree can be found [here](https://goo.gl/1dqvzz). Input The first line contains one integer n — the number of vertices in the tree (3 ≤ n ≤ 1 000). Each of the next n - 1 lines contains one integer pi (1 ≤ i ≤ n - 1) — the index of the parent of the i + 1-th vertex (1 ≤ pi ≤ i). Vertex 1 is the root. It's guaranteed that the root has at least 2 children. Output Print "Yes" if the tree is a spruce and "No" otherwise. Examples Input 4 1 1 1 Output Yes Input 7 1 1 1 2 2 2 Output No Input 8 1 1 1 1 3 3 3 Output Yes Note The first example: <image> The second example: <image> It is not a spruce, because the non-leaf vertex 1 has only 2 leaf children. The third example: <image>
instruction
0
102,626
13
205,252
Tags: implementation, trees Correct Solution: ``` from collections import defaultdict N = int(input()) Check, MyDict = [True] + [False] * (N - 1), defaultdict(list) for i in range(N - 1): Temp = int(input()) MyDict[Temp].append(i + 2) Check[Temp - 1] = True for key in MyDict: if len([True for value in MyDict[key] if Check[value - 1] == False]) < 3: print("NO") exit() print("YES") # Show you deserve being the best to whom doesn't believe in you. # Location: WTF is this JAVA project. Data Mining with JAVA? # Like participating with Pride in car races ```
output
1
102,626
13
205,253
Provide tags and a correct Python 3 solution for this coding contest problem. Consider a rooted tree. A rooted tree has one special vertex called the root. All edges are directed from the root. Vertex u is called a child of vertex v and vertex v is called a parent of vertex u if there exists a directed edge from v to u. A vertex is called a leaf if it doesn't have children and has a parent. Let's call a rooted tree a spruce if its every non-leaf vertex has at least 3 leaf children. You are given a rooted tree, check whether it's a spruce. The definition of a rooted tree can be found [here](https://goo.gl/1dqvzz). Input The first line contains one integer n — the number of vertices in the tree (3 ≤ n ≤ 1 000). Each of the next n - 1 lines contains one integer pi (1 ≤ i ≤ n - 1) — the index of the parent of the i + 1-th vertex (1 ≤ pi ≤ i). Vertex 1 is the root. It's guaranteed that the root has at least 2 children. Output Print "Yes" if the tree is a spruce and "No" otherwise. Examples Input 4 1 1 1 Output Yes Input 7 1 1 1 2 2 2 Output No Input 8 1 1 1 1 3 3 3 Output Yes Note The first example: <image> The second example: <image> It is not a spruce, because the non-leaf vertex 1 has only 2 leaf children. The third example: <image>
instruction
0
102,627
13
205,254
Tags: implementation, trees Correct Solution: ``` import sys sys.setrecursionlimit(10000) n=int(input()) vs = {} for c in range(2, n+1): p = int(input()) if p in vs: vs[p].append(c) else: vs[p] = [c] def check(n): if n not in vs: return 1 ch = vs[n] s = 0 for c in ch: r = check(c) if r == -1: return -1 s+=r if s >= 3: return 0 return -1 print('Yes' if check(1) == 0 else 'No') ```
output
1
102,627
13
205,255
Provide tags and a correct Python 3 solution for this coding contest problem. Consider a rooted tree. A rooted tree has one special vertex called the root. All edges are directed from the root. Vertex u is called a child of vertex v and vertex v is called a parent of vertex u if there exists a directed edge from v to u. A vertex is called a leaf if it doesn't have children and has a parent. Let's call a rooted tree a spruce if its every non-leaf vertex has at least 3 leaf children. You are given a rooted tree, check whether it's a spruce. The definition of a rooted tree can be found [here](https://goo.gl/1dqvzz). Input The first line contains one integer n — the number of vertices in the tree (3 ≤ n ≤ 1 000). Each of the next n - 1 lines contains one integer pi (1 ≤ i ≤ n - 1) — the index of the parent of the i + 1-th vertex (1 ≤ pi ≤ i). Vertex 1 is the root. It's guaranteed that the root has at least 2 children. Output Print "Yes" if the tree is a spruce and "No" otherwise. Examples Input 4 1 1 1 Output Yes Input 7 1 1 1 2 2 2 Output No Input 8 1 1 1 1 3 3 3 Output Yes Note The first example: <image> The second example: <image> It is not a spruce, because the non-leaf vertex 1 has only 2 leaf children. The third example: <image>
instruction
0
102,628
13
205,256
Tags: implementation, trees Correct Solution: ``` # -*- coding: utf-8 -*- """ Created on Thu Jun 11 11:00:21 2020 @author: Harshal """ import collections,sys n=int(input()) graph=collections.defaultdict(list) for i in range(2,n+1): a=int(input()) graph[a].append(i) for i in range(1,n+1): if i not in graph: graph[i]=[] que=[1] while que: node=que.pop() blank=0 for n in graph[node]: if len(graph[n])==0: blank+=1 else: que.append(n) if blank<3: print("No") sys.exit() print("Yes") ```
output
1
102,628
13
205,257
Provide tags and a correct Python 3 solution for this coding contest problem. Consider a rooted tree. A rooted tree has one special vertex called the root. All edges are directed from the root. Vertex u is called a child of vertex v and vertex v is called a parent of vertex u if there exists a directed edge from v to u. A vertex is called a leaf if it doesn't have children and has a parent. Let's call a rooted tree a spruce if its every non-leaf vertex has at least 3 leaf children. You are given a rooted tree, check whether it's a spruce. The definition of a rooted tree can be found [here](https://goo.gl/1dqvzz). Input The first line contains one integer n — the number of vertices in the tree (3 ≤ n ≤ 1 000). Each of the next n - 1 lines contains one integer pi (1 ≤ i ≤ n - 1) — the index of the parent of the i + 1-th vertex (1 ≤ pi ≤ i). Vertex 1 is the root. It's guaranteed that the root has at least 2 children. Output Print "Yes" if the tree is a spruce and "No" otherwise. Examples Input 4 1 1 1 Output Yes Input 7 1 1 1 2 2 2 Output No Input 8 1 1 1 1 3 3 3 Output Yes Note The first example: <image> The second example: <image> It is not a spruce, because the non-leaf vertex 1 has only 2 leaf children. The third example: <image>
instruction
0
102,629
13
205,258
Tags: implementation, trees Correct Solution: ``` import sys from collections import Counter L=sys.stdin.readlines() n=int(L[0]) l=list(map(lambda x:int(x),L[1:]) ) cnt=Counter(l) cntl=Counter([l[i-2] for i in range(2,n+1) if i not in cnt ] ) for a in cnt: if cntl[a]<3: print("No") break else: print("Yes") ```
output
1
102,629
13
205,259