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 a correct Python 3 solution for this coding contest problem. A rooted binary tree is a tree with a root node in which every node has at most two children. Your task is to write a program which reads a rooted binary tree T and prints the following information for each node u of T: * node ID of u * parent of u * sibling of u * the number of children of u * depth of u * height of u * node type (root, internal node or leaf) If two nodes have the same parent, they are siblings. Here, if u and v have the same parent, we say u is a sibling of v (vice versa). The height of a node in a tree is the number of edges on the longest simple downward path from the node to a leaf. Here, the given binary tree consists of n nodes and evey node has a unique ID from 0 to n-1. Constraints * 1 ≤ n ≤ 25 Input The first line of the input includes an integer n, the number of nodes of the tree. In the next n lines, the information of each node is given in the following format: id left right id is the node ID, left is ID of the left child and right is ID of the right child. If the node does not have the left (right) child, the left(right) is indicated by -1. Output Print the information of each node in the following format: node id: parent = p, sibling = s, degree = deg, depth = dep, height = h, type p is ID of its parent. If the node does not have a parent, print -1. s is ID of its sibling. If the node does not have a sibling, print -1. deg, dep and h are the number of children, depth and height of the node respectively. type is a type of nodes represented by a string (root, internal node or leaf. If the root can be considered as a leaf or an internal node, print root. Please follow the format presented in a sample output below. Example Input 9 0 1 4 1 2 3 2 -1 -1 3 -1 -1 4 5 8 5 6 7 6 -1 -1 7 -1 -1 8 -1 -1 Output node 0: parent = -1, sibling = -1, degree = 2, depth = 0, height = 3, root node 1: parent = 0, sibling = 4, degree = 2, depth = 1, height = 1, internal node node 2: parent = 1, sibling = 3, degree = 0, depth = 2, height = 0, leaf node 3: parent = 1, sibling = 2, degree = 0, depth = 2, height = 0, leaf node 4: parent = 0, sibling = 1, degree = 2, depth = 1, height = 2, internal node node 5: parent = 4, sibling = 8, degree = 2, depth = 2, height = 1, internal node node 6: parent = 5, sibling = 7, degree = 0, depth = 3, height = 0, leaf node 7: parent = 5, sibling = 6, degree = 0, depth = 3, height = 0, leaf node 8: parent = 4, sibling = 5, degree = 0, depth = 2, height = 0, leaf
instruction
0
51,282
13
102,564
"Correct Solution: ``` class Node: def __init__(self, parent, left, right): self.parent, self.left, self.right = parent, left, right N = int(input()) T = [Node(None, None, None) for _ in range(N)] for t in T: i, left, right = map(int, input().split()) if left != -1: T[i].left = left T[left].parent = i if right != -1: T[i].right = right T[right].parent = i def get_sibling(i): if T[i].parent == None: return -1 if i != T[T[i].parent].left and T[T[i].parent].left != None: return T[T[i].parent].left if i != T[T[i].parent].right and T[T[i].parent].right != None: return T[T[i].parent].right return -1 def get_depth(i): depth = 0 while T[i].parent != None: depth += 1 i = T[i].parent return depth def get_height(i): h1, h2 = 0, 0 if T[i].left != None: h1 = get_height(T[i].left) + 1 if T[i].right != None: h2 = get_height(T[i].right) + 1 return max(h1, h2) for i, t in enumerate(T): print('node {}:'.format(i), end=' ') parent = t.parent if t.parent != None else -1 print('parent = {},'.format(parent), end=' ') sibling = get_sibling(i) print('sibling = {},'.format(sibling), end=' ') degree = 0 if t.left != None: degree += 1 if t.right != None: degree += 1 print('degree = {},'.format(degree), end=' ') depth = get_depth(i) print('depth = {},'.format(depth), end=' ') height = get_height(i) print('height = {},'.format(height), end=' ') if t.parent == None: node = 'root' elif t.left == None and t.right == None: node = 'leaf' else: node = 'internal node' print(node) ```
output
1
51,282
13
102,565
Provide a correct Python 3 solution for this coding contest problem. A rooted binary tree is a tree with a root node in which every node has at most two children. Your task is to write a program which reads a rooted binary tree T and prints the following information for each node u of T: * node ID of u * parent of u * sibling of u * the number of children of u * depth of u * height of u * node type (root, internal node or leaf) If two nodes have the same parent, they are siblings. Here, if u and v have the same parent, we say u is a sibling of v (vice versa). The height of a node in a tree is the number of edges on the longest simple downward path from the node to a leaf. Here, the given binary tree consists of n nodes and evey node has a unique ID from 0 to n-1. Constraints * 1 ≤ n ≤ 25 Input The first line of the input includes an integer n, the number of nodes of the tree. In the next n lines, the information of each node is given in the following format: id left right id is the node ID, left is ID of the left child and right is ID of the right child. If the node does not have the left (right) child, the left(right) is indicated by -1. Output Print the information of each node in the following format: node id: parent = p, sibling = s, degree = deg, depth = dep, height = h, type p is ID of its parent. If the node does not have a parent, print -1. s is ID of its sibling. If the node does not have a sibling, print -1. deg, dep and h are the number of children, depth and height of the node respectively. type is a type of nodes represented by a string (root, internal node or leaf. If the root can be considered as a leaf or an internal node, print root. Please follow the format presented in a sample output below. Example Input 9 0 1 4 1 2 3 2 -1 -1 3 -1 -1 4 5 8 5 6 7 6 -1 -1 7 -1 -1 8 -1 -1 Output node 0: parent = -1, sibling = -1, degree = 2, depth = 0, height = 3, root node 1: parent = 0, sibling = 4, degree = 2, depth = 1, height = 1, internal node node 2: parent = 1, sibling = 3, degree = 0, depth = 2, height = 0, leaf node 3: parent = 1, sibling = 2, degree = 0, depth = 2, height = 0, leaf node 4: parent = 0, sibling = 1, degree = 2, depth = 1, height = 2, internal node node 5: parent = 4, sibling = 8, degree = 2, depth = 2, height = 1, internal node node 6: parent = 5, sibling = 7, degree = 0, depth = 3, height = 0, leaf node 7: parent = 5, sibling = 6, degree = 0, depth = 3, height = 0, leaf node 8: parent = 4, sibling = 5, degree = 0, depth = 2, height = 0, leaf
instruction
0
51,283
13
102,566
"Correct Solution: ``` N = int(input()) class Node(): def __init__(self, parent = -1, left = -1, right = -1): self.parent = parent self.left = left self.right = right binary_tree = [Node() for _ in range(N)] for _ in range(N): node_input = input() id, left, right = map(int, node_input.split()) binary_tree[id].left = left binary_tree[id].right = right if left != -1: binary_tree[left].parent = id if right != -1: binary_tree[right].parent = id def set_depth(id, depth): if id == -1: return D[id] = depth set_depth(binary_tree[id].left, depth+1) set_depth(binary_tree[id].right, depth+1) def set_height(id): h1, h2 = 0, 0 if binary_tree[id].left != -1: h1 = set_height(binary_tree[id].left) + 1 if binary_tree[id].right != -1: h2 = set_height(binary_tree[id].right) + 1 H[id] = max(h1, h2) return H[id] D = [0 for i in range(N)] H = [0 for i in range(N)] for id in range(N): if binary_tree[id].parent == -1: set_depth(id, 0) set_height(id) break def get_sibling(id): parent_id = node.parent if parent_id == -1: return -1 if binary_tree[parent_id].left != id: return binary_tree[parent_id].left else: return binary_tree[parent_id].right def get_degree(node): degree = 0 if node.left != -1: degree += 1 if node.right != -1: degree += 1 return degree def get_type(node, dgree): if node.parent == -1: return "root" if degree == 0: return "leaf" return "internal node" for id in range(N): node = binary_tree[id] parent_id = node.parent sibling_id = get_sibling(id) degree = get_degree(node) node_type = get_type(node, degree) print("node {}: parent = {}, sibling = {}, degree = {}, depth = {}, height = {}, {}".format(id, parent_id, sibling_id, degree, D[id], H[id], node_type)) ```
output
1
51,283
13
102,567
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A rooted binary tree is a tree with a root node in which every node has at most two children. Your task is to write a program which reads a rooted binary tree T and prints the following information for each node u of T: * node ID of u * parent of u * sibling of u * the number of children of u * depth of u * height of u * node type (root, internal node or leaf) If two nodes have the same parent, they are siblings. Here, if u and v have the same parent, we say u is a sibling of v (vice versa). The height of a node in a tree is the number of edges on the longest simple downward path from the node to a leaf. Here, the given binary tree consists of n nodes and evey node has a unique ID from 0 to n-1. Constraints * 1 ≤ n ≤ 25 Input The first line of the input includes an integer n, the number of nodes of the tree. In the next n lines, the information of each node is given in the following format: id left right id is the node ID, left is ID of the left child and right is ID of the right child. If the node does not have the left (right) child, the left(right) is indicated by -1. Output Print the information of each node in the following format: node id: parent = p, sibling = s, degree = deg, depth = dep, height = h, type p is ID of its parent. If the node does not have a parent, print -1. s is ID of its sibling. If the node does not have a sibling, print -1. deg, dep and h are the number of children, depth and height of the node respectively. type is a type of nodes represented by a string (root, internal node or leaf. If the root can be considered as a leaf or an internal node, print root. Please follow the format presented in a sample output below. Example Input 9 0 1 4 1 2 3 2 -1 -1 3 -1 -1 4 5 8 5 6 7 6 -1 -1 7 -1 -1 8 -1 -1 Output node 0: parent = -1, sibling = -1, degree = 2, depth = 0, height = 3, root node 1: parent = 0, sibling = 4, degree = 2, depth = 1, height = 1, internal node node 2: parent = 1, sibling = 3, degree = 0, depth = 2, height = 0, leaf node 3: parent = 1, sibling = 2, degree = 0, depth = 2, height = 0, leaf node 4: parent = 0, sibling = 1, degree = 2, depth = 1, height = 2, internal node node 5: parent = 4, sibling = 8, degree = 2, depth = 2, height = 1, internal node node 6: parent = 5, sibling = 7, degree = 0, depth = 3, height = 0, leaf node 7: parent = 5, sibling = 6, degree = 0, depth = 3, height = 0, leaf node 8: parent = 4, sibling = 5, degree = 0, depth = 2, height = 0, leaf Submitted Solution: ``` class node(): def __init__(self, id, parent, child, depth, type_t, sibling, height=0): self.id = id self.parent = parent self.child = child self.depth = depth self.type_t = type_t self.sibling = sibling self.height = height def add(t, d, i, parent, depth, sibling): type_t = 'internal node' if d[i][1] == -1 and d[i][2] == -1: type_t = 'leaf' if depth == 0: type_t = 'root' child = [] if d[i][1] >= 0: child.append(d[i][1]) if d[i][2] >= 0: child.append(d[i][2]) new_node = node(i, parent, child, depth, type_t, sibling) t.append(new_node) sib = -1 if len(child) == 1: add(t, d, child[0], i, depth + 1, sib) elif len(child) == 2: add(t, d, child[0], i, depth + 1, child[1]) add(t, d, child[1], i, depth + 1, child[0]) def calc_height(t, i): if len(t[i].child) == 0: return 0 max_h = -1 for c in t[i].child: max_h = max(max_h, calc_height(t, c)) return max_h + 1 N = int(input()) tree = [] data = [[] for i in range(N)] for i in range(N): data[i] = [int(i) for i in input().split()] data.sort(key=lambda x: x[0]) root = [True for i in range(N)] for d in data: for c in d[1:]: if c == -1: continue root[c] = False root_index = root.index(True) add(tree, data, root_index, -1, 0, -1) tree.sort(key=lambda x: x.id) for i in range(N): h = calc_height(tree, i) tree[i].height = h for t in tree: print(f'node {t.id}: parent = {t.parent}, sibling = {t.sibling},' f' degree = {len(t.child)}, depth = {t.depth},' f' height = {t.height}, {t.type_t}') ```
instruction
0
51,284
13
102,568
Yes
output
1
51,284
13
102,569
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A rooted binary tree is a tree with a root node in which every node has at most two children. Your task is to write a program which reads a rooted binary tree T and prints the following information for each node u of T: * node ID of u * parent of u * sibling of u * the number of children of u * depth of u * height of u * node type (root, internal node or leaf) If two nodes have the same parent, they are siblings. Here, if u and v have the same parent, we say u is a sibling of v (vice versa). The height of a node in a tree is the number of edges on the longest simple downward path from the node to a leaf. Here, the given binary tree consists of n nodes and evey node has a unique ID from 0 to n-1. Constraints * 1 ≤ n ≤ 25 Input The first line of the input includes an integer n, the number of nodes of the tree. In the next n lines, the information of each node is given in the following format: id left right id is the node ID, left is ID of the left child and right is ID of the right child. If the node does not have the left (right) child, the left(right) is indicated by -1. Output Print the information of each node in the following format: node id: parent = p, sibling = s, degree = deg, depth = dep, height = h, type p is ID of its parent. If the node does not have a parent, print -1. s is ID of its sibling. If the node does not have a sibling, print -1. deg, dep and h are the number of children, depth and height of the node respectively. type is a type of nodes represented by a string (root, internal node or leaf. If the root can be considered as a leaf or an internal node, print root. Please follow the format presented in a sample output below. Example Input 9 0 1 4 1 2 3 2 -1 -1 3 -1 -1 4 5 8 5 6 7 6 -1 -1 7 -1 -1 8 -1 -1 Output node 0: parent = -1, sibling = -1, degree = 2, depth = 0, height = 3, root node 1: parent = 0, sibling = 4, degree = 2, depth = 1, height = 1, internal node node 2: parent = 1, sibling = 3, degree = 0, depth = 2, height = 0, leaf node 3: parent = 1, sibling = 2, degree = 0, depth = 2, height = 0, leaf node 4: parent = 0, sibling = 1, degree = 2, depth = 1, height = 2, internal node node 5: parent = 4, sibling = 8, degree = 2, depth = 2, height = 1, internal node node 6: parent = 5, sibling = 7, degree = 0, depth = 3, height = 0, leaf node 7: parent = 5, sibling = 6, degree = 0, depth = 3, height = 0, leaf node 8: parent = 4, sibling = 5, degree = 0, depth = 2, height = 0, leaf Submitted Solution: ``` from sys import stdin class Node(): NIL = -1 def __init__(self, p=NIL, l=NIL, r=NIL, d=-1, h=-1): self.p = p self.l = l self.r = r self.d = d self.h = h def __repr__(self): return "Node({}, {}, {}, {})".format(self.p, self.l, self.r, self.d) def root_of(T): return [u.p for u in T].index(Node.NIL) def sibling_of(T, id): p = T[T[id].p] return p.r if p.l == id else p.l def degree_of(T, id): l = 0 if T[id].l == Node.NIL else 1 r = 0 if T[id].r == Node.NIL else 1 return l + r def calc_depth(T): def rec(id, depth): nonlocal T T[id].d = depth if T[id].l != Node.NIL: rec(T[id].l, depth + 1) if T[id].r != Node.NIL: rec(T[id].r, depth + 1) rec(root_of(T), 0) def calc_height(T): def rec(id): nonlocal T l = 0 if T[id].l == Node.NIL else rec(T[id].l) + 1 r = 0 if T[id].r == Node.NIL else rec(T[id].r) + 1 T[id].h = max(l, r) return T[id].h rec(root_of(T)) def type_of(T, id): if T[id].p == Node.NIL: return "root" elif T[id].l == Node.NIL and T[id].r == Node.NIL: return "leaf" else: return "internal node" def read_nodes(T): for line in stdin: id, l, r = [int(x) for x in line.split()] T[id].l = l if l != Node.NIL: T[l].p = id T[id].r = r if r != Node.NIL: T[r].p = id def print_nodes(T): for id in range(len(T)): print("node {}: ".format(id), end="") print("parent = {}, ".format(T[id].p), end="") print("sibling = {}, ".format(sibling_of(T, id)), end="") print("degree = {}, ".format(degree_of(T, id)), end="") print("depth = {}, ".format(T[id].d), end="") print("height = {}, ".format(T[id].h), end="") print(type_of(T, id)) def main(): n = int(stdin.readline()) T = [Node() for _ in range(n)] read_nodes(T) calc_depth(T) calc_height(T) print_nodes(T) main() ```
instruction
0
51,285
13
102,570
Yes
output
1
51,285
13
102,571
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A rooted binary tree is a tree with a root node in which every node has at most two children. Your task is to write a program which reads a rooted binary tree T and prints the following information for each node u of T: * node ID of u * parent of u * sibling of u * the number of children of u * depth of u * height of u * node type (root, internal node or leaf) If two nodes have the same parent, they are siblings. Here, if u and v have the same parent, we say u is a sibling of v (vice versa). The height of a node in a tree is the number of edges on the longest simple downward path from the node to a leaf. Here, the given binary tree consists of n nodes and evey node has a unique ID from 0 to n-1. Constraints * 1 ≤ n ≤ 25 Input The first line of the input includes an integer n, the number of nodes of the tree. In the next n lines, the information of each node is given in the following format: id left right id is the node ID, left is ID of the left child and right is ID of the right child. If the node does not have the left (right) child, the left(right) is indicated by -1. Output Print the information of each node in the following format: node id: parent = p, sibling = s, degree = deg, depth = dep, height = h, type p is ID of its parent. If the node does not have a parent, print -1. s is ID of its sibling. If the node does not have a sibling, print -1. deg, dep and h are the number of children, depth and height of the node respectively. type is a type of nodes represented by a string (root, internal node or leaf. If the root can be considered as a leaf or an internal node, print root. Please follow the format presented in a sample output below. Example Input 9 0 1 4 1 2 3 2 -1 -1 3 -1 -1 4 5 8 5 6 7 6 -1 -1 7 -1 -1 8 -1 -1 Output node 0: parent = -1, sibling = -1, degree = 2, depth = 0, height = 3, root node 1: parent = 0, sibling = 4, degree = 2, depth = 1, height = 1, internal node node 2: parent = 1, sibling = 3, degree = 0, depth = 2, height = 0, leaf node 3: parent = 1, sibling = 2, degree = 0, depth = 2, height = 0, leaf node 4: parent = 0, sibling = 1, degree = 2, depth = 1, height = 2, internal node node 5: parent = 4, sibling = 8, degree = 2, depth = 2, height = 1, internal node node 6: parent = 5, sibling = 7, degree = 0, depth = 3, height = 0, leaf node 7: parent = 5, sibling = 6, degree = 0, depth = 3, height = 0, leaf node 8: parent = 4, sibling = 5, degree = 0, depth = 2, height = 0, leaf Submitted Solution: ``` class Node(): "node of the tree structure" def __init__(self, parent = -1, left = -1, right = -1): self.parent = parent self.left = left self.right = right def setHeight(u): h1 = 0 h2 = 0 if node_list[u].right != -1: h1 = setHeight(node_list[u].right) + 1 if node_list[u].left != -1: h2 = setHeight(node_list[u].left) + 1 return max(h1,h2) def getSibling(u): if node_list[u].parent == -1: return -1 if node_list[node_list[u].parent].left != -1 and node_list[node_list[u].parent].left != u: return node_list[node_list[u].parent].left if node_list[node_list[u].parent].right != -1 and node_list[node_list[u].parent].right != u: return node_list[node_list[u].parent].right return -1 def getDegree(u): count = 0 if node_list[u].left != -1: count += 1 if node_list[u].right != -1: count += 1 return count def getDepth(u): count = 0 while node_list[u].parent != -1: count += 1 u = node_list[u].parent return count def getType(u): if node_list[u].parent == -1: return "root" if node_list[u].left == -1 and node_list[u].right == -1: return "leaf" return "internal node" n = int(input()) node_list = [] for i in range(n): node = Node() node_list.append(node) for i in range(n): a,b,c = map(int, input().split()) node_list[a].left = b node_list[a].right = c if b != -1: node_list[b].parent = a if c != -1: node_list[c].parent = a height_list = [-1]*n for i in range(n): print("node", str(i)+":", "parent =", str(node_list[i].parent) + ",", "sibling =", str(getSibling(i)) + ",", "degree =", str(getDegree(i)) + ",", "depth =", str(getDepth(i)) + ",", "height =", str(setHeight(i)) + ",", getType(i)) ```
instruction
0
51,286
13
102,572
Yes
output
1
51,286
13
102,573
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A rooted binary tree is a tree with a root node in which every node has at most two children. Your task is to write a program which reads a rooted binary tree T and prints the following information for each node u of T: * node ID of u * parent of u * sibling of u * the number of children of u * depth of u * height of u * node type (root, internal node or leaf) If two nodes have the same parent, they are siblings. Here, if u and v have the same parent, we say u is a sibling of v (vice versa). The height of a node in a tree is the number of edges on the longest simple downward path from the node to a leaf. Here, the given binary tree consists of n nodes and evey node has a unique ID from 0 to n-1. Constraints * 1 ≤ n ≤ 25 Input The first line of the input includes an integer n, the number of nodes of the tree. In the next n lines, the information of each node is given in the following format: id left right id is the node ID, left is ID of the left child and right is ID of the right child. If the node does not have the left (right) child, the left(right) is indicated by -1. Output Print the information of each node in the following format: node id: parent = p, sibling = s, degree = deg, depth = dep, height = h, type p is ID of its parent. If the node does not have a parent, print -1. s is ID of its sibling. If the node does not have a sibling, print -1. deg, dep and h are the number of children, depth and height of the node respectively. type is a type of nodes represented by a string (root, internal node or leaf. If the root can be considered as a leaf or an internal node, print root. Please follow the format presented in a sample output below. Example Input 9 0 1 4 1 2 3 2 -1 -1 3 -1 -1 4 5 8 5 6 7 6 -1 -1 7 -1 -1 8 -1 -1 Output node 0: parent = -1, sibling = -1, degree = 2, depth = 0, height = 3, root node 1: parent = 0, sibling = 4, degree = 2, depth = 1, height = 1, internal node node 2: parent = 1, sibling = 3, degree = 0, depth = 2, height = 0, leaf node 3: parent = 1, sibling = 2, degree = 0, depth = 2, height = 0, leaf node 4: parent = 0, sibling = 1, degree = 2, depth = 1, height = 2, internal node node 5: parent = 4, sibling = 8, degree = 2, depth = 2, height = 1, internal node node 6: parent = 5, sibling = 7, degree = 0, depth = 3, height = 0, leaf node 7: parent = 5, sibling = 6, degree = 0, depth = 3, height = 0, leaf node 8: parent = 4, sibling = 5, degree = 0, depth = 2, height = 0, leaf Submitted Solution: ``` import sys sys.setrecursionlimit(10**7) class Node: def __init__(self, parent, left, right): self.parent = parent self.left = left self.right = right def get_height(T, H, u): h1, h2 = 0, 0 if T[u].right is not None: h1 = get_height(T, H, T[u].right) + 1 if T[u].left is not None: h2 = get_height(T, H, T[u].left) + 1 h = max(h1, h2) H[u] = h return h def get_depth(T, D, u, d): D[u] = d if T[u].right is not None: get_depth(T, D, T[u].right, d+1) if T[u].left is not None: get_depth(T, D, T[u].left, d+1) def ret_sibling(T, u): parent = T[u].parent if parent is None: return -1 if T[parent].left != u: ret = T[parent].left else: ret = T[parent].right if ret is None: return -1 return ret def ret_degree(T, u): ret = 2 if T[u].left is None: ret -= 1 if T[u].right is None: ret -= 1 return ret n = int(input()) T = {k: Node(None, None, None) for k in range(n)} for _ in range(n): tmp = list(map(int, input().split())) if tmp[1] != -1: T[tmp[0]].left = tmp[1] T[tmp[1]].parent = tmp[0] if tmp[2] != -1: T[tmp[0]].right = tmp[2] T[tmp[2]].parent = tmp[0] for k, v in T.items(): if v.parent is None: ROOT = k break D = {} get_depth(T, D, ROOT, 0) H = {} get_height(T, H, ROOT) def print_for_a_node(u): if T[u].parent is None: parent = -1 else: parent = T[u].parent sib = ret_sibling(T, u) deg = ret_degree(T, u) node_type = 'internal node' if deg != 0 else 'leaf' if parent == -1: node_type = 'root' print(f'node {u}: parent = {parent}, sibling = {sib}, degree = {deg}, depth = {D[u]}, height = {H[u]}, {node_type}') for node in range(n): print_for_a_node(node) ```
instruction
0
51,287
13
102,574
Yes
output
1
51,287
13
102,575
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A rooted binary tree is a tree with a root node in which every node has at most two children. Your task is to write a program which reads a rooted binary tree T and prints the following information for each node u of T: * node ID of u * parent of u * sibling of u * the number of children of u * depth of u * height of u * node type (root, internal node or leaf) If two nodes have the same parent, they are siblings. Here, if u and v have the same parent, we say u is a sibling of v (vice versa). The height of a node in a tree is the number of edges on the longest simple downward path from the node to a leaf. Here, the given binary tree consists of n nodes and evey node has a unique ID from 0 to n-1. Constraints * 1 ≤ n ≤ 25 Input The first line of the input includes an integer n, the number of nodes of the tree. In the next n lines, the information of each node is given in the following format: id left right id is the node ID, left is ID of the left child and right is ID of the right child. If the node does not have the left (right) child, the left(right) is indicated by -1. Output Print the information of each node in the following format: node id: parent = p, sibling = s, degree = deg, depth = dep, height = h, type p is ID of its parent. If the node does not have a parent, print -1. s is ID of its sibling. If the node does not have a sibling, print -1. deg, dep and h are the number of children, depth and height of the node respectively. type is a type of nodes represented by a string (root, internal node or leaf. If the root can be considered as a leaf or an internal node, print root. Please follow the format presented in a sample output below. Example Input 9 0 1 4 1 2 3 2 -1 -1 3 -1 -1 4 5 8 5 6 7 6 -1 -1 7 -1 -1 8 -1 -1 Output node 0: parent = -1, sibling = -1, degree = 2, depth = 0, height = 3, root node 1: parent = 0, sibling = 4, degree = 2, depth = 1, height = 1, internal node node 2: parent = 1, sibling = 3, degree = 0, depth = 2, height = 0, leaf node 3: parent = 1, sibling = 2, degree = 0, depth = 2, height = 0, leaf node 4: parent = 0, sibling = 1, degree = 2, depth = 1, height = 2, internal node node 5: parent = 4, sibling = 8, degree = 2, depth = 2, height = 1, internal node node 6: parent = 5, sibling = 7, degree = 0, depth = 3, height = 0, leaf node 7: parent = 5, sibling = 6, degree = 0, depth = 3, height = 0, leaf node 8: parent = 4, sibling = 5, degree = 0, depth = 2, height = 0, leaf Submitted Solution: ``` import sys readline = sys.stdin.readline class Tree: __slots__ = ['id', 'p', 'sibling', 'degree', 'depth', 'height', 'type', 'c'] def __init__(self, id): self.id = id self.p = -1 self.sibling = -1 self.degree = 0 self.depth = 0 self.height = 0 self.type = "leaf" self.c = [] def __str__(self): return f"node {self.id}: parent = {self.p}, sibling = {self.sibling}, degree = {self.degree}, depth = {self.depth}, height = {self.height}, {self.type}" def solve(): n = int(input()) tree = tuple(Tree(i) for i in range(n)) for _ in range(n): id, *c = map(int, readline().replace("-1", "").split()) if c != []: tree[id].type = "internal node" tree[id].c = c for j in c: tree[j].p = id len_c = len(c) tree[id].degree = len_c if len_c == 2: tree[c[0]].sibling = c[1] tree[c[1]].sibling = c[0] rootget = lambda x: rootget(x) if tree[x].p != -1 else x root = rootget(0) tree[root].type = "root" def depth_height_check(id, d): d += 1 height = 0 for i in tree[id].c: tree[i].depth = d if tree[i].type != "leaf": tree[i].height = depth_height_check(i, d) + 1 height = max(height, tree[i].height) return height tree[root].height = depth_height_check(root, 0) + 1 if n > 1 else 0 print("\n".join(map(str, tree))) solve() ```
instruction
0
51,288
13
102,576
No
output
1
51,288
13
102,577
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A rooted binary tree is a tree with a root node in which every node has at most two children. Your task is to write a program which reads a rooted binary tree T and prints the following information for each node u of T: * node ID of u * parent of u * sibling of u * the number of children of u * depth of u * height of u * node type (root, internal node or leaf) If two nodes have the same parent, they are siblings. Here, if u and v have the same parent, we say u is a sibling of v (vice versa). The height of a node in a tree is the number of edges on the longest simple downward path from the node to a leaf. Here, the given binary tree consists of n nodes and evey node has a unique ID from 0 to n-1. Constraints * 1 ≤ n ≤ 25 Input The first line of the input includes an integer n, the number of nodes of the tree. In the next n lines, the information of each node is given in the following format: id left right id is the node ID, left is ID of the left child and right is ID of the right child. If the node does not have the left (right) child, the left(right) is indicated by -1. Output Print the information of each node in the following format: node id: parent = p, sibling = s, degree = deg, depth = dep, height = h, type p is ID of its parent. If the node does not have a parent, print -1. s is ID of its sibling. If the node does not have a sibling, print -1. deg, dep and h are the number of children, depth and height of the node respectively. type is a type of nodes represented by a string (root, internal node or leaf. If the root can be considered as a leaf or an internal node, print root. Please follow the format presented in a sample output below. Example Input 9 0 1 4 1 2 3 2 -1 -1 3 -1 -1 4 5 8 5 6 7 6 -1 -1 7 -1 -1 8 -1 -1 Output node 0: parent = -1, sibling = -1, degree = 2, depth = 0, height = 3, root node 1: parent = 0, sibling = 4, degree = 2, depth = 1, height = 1, internal node node 2: parent = 1, sibling = 3, degree = 0, depth = 2, height = 0, leaf node 3: parent = 1, sibling = 2, degree = 0, depth = 2, height = 0, leaf node 4: parent = 0, sibling = 1, degree = 2, depth = 1, height = 2, internal node node 5: parent = 4, sibling = 8, degree = 2, depth = 2, height = 1, internal node node 6: parent = 5, sibling = 7, degree = 0, depth = 3, height = 0, leaf node 7: parent = 5, sibling = 6, degree = 0, depth = 3, height = 0, leaf node 8: parent = 4, sibling = 5, degree = 0, depth = 2, height = 0, leaf Submitted Solution: ``` N = int(input()) M = [] type = ['root','internal node','leaf'] class node: def __init__(self,idx,parent,left,right): self.idx = idx self.parent = parent self.left = left self.right= right self.sibling = -1 self.degree= 0 self.depth = 0 self.height = 0 self.type=-1 def tostr(self): print('node %d: parent = %d, sibling = %d, degree = %d, depth = %d, height = %d, %s' % (self.idx, self.parent, self.sibling, self.degree, self.depth, self.height, type[self.type])) tree = [[] for x in range(N)] #'idx, parent, sibling, degree, depth, height, type' for a in range(N): idx,left,right = map(int,input().strip().split(' ')) tree[idx] = node(idx, -1, left,right) for a in range(N): nd = tree[a] if nd.left != -1: tree[nd.left].parent = a if nd.right != -1: tree[nd.right].parent = a if nd.left != -1: tree[nd.left].sibling = nd.right if nd.right != -1: tree[nd.right].sibling = nd.left if nd.left == nd.right : nd.type=2 nd.degree=0 else: nd.type=1 if nd.left == -1 or nd.right == -1: nd.degree = 1 else: nd.degree = 2 root = '' for a in range(N): if tree[a].parent == -1: root = a tree[root].type=0 def search(root,depth): root = tree[root] root.depth = depth if root.type == 2: return else: if root.right == -1 and root.left == -1: return search(root.right,depth+1) search(root.left,depth+1) search(root,0) def height(root,hei): root = tree[root] if root.type==2 or (root.right == -1 and root.left == -1): root.height=0 return hei else: if root.left == -1: return height(root.right,hei+1) elif root.right == -1: return height(root.left,hei+1) else: return max(height(root.left,hei+1),height(root.right,hei+1)) for i in range(N): tree[i].height=height(i,0) for a in range(N): tree[a].tostr() ```
instruction
0
51,289
13
102,578
No
output
1
51,289
13
102,579
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A rooted binary tree is a tree with a root node in which every node has at most two children. Your task is to write a program which reads a rooted binary tree T and prints the following information for each node u of T: * node ID of u * parent of u * sibling of u * the number of children of u * depth of u * height of u * node type (root, internal node or leaf) If two nodes have the same parent, they are siblings. Here, if u and v have the same parent, we say u is a sibling of v (vice versa). The height of a node in a tree is the number of edges on the longest simple downward path from the node to a leaf. Here, the given binary tree consists of n nodes and evey node has a unique ID from 0 to n-1. Constraints * 1 ≤ n ≤ 25 Input The first line of the input includes an integer n, the number of nodes of the tree. In the next n lines, the information of each node is given in the following format: id left right id is the node ID, left is ID of the left child and right is ID of the right child. If the node does not have the left (right) child, the left(right) is indicated by -1. Output Print the information of each node in the following format: node id: parent = p, sibling = s, degree = deg, depth = dep, height = h, type p is ID of its parent. If the node does not have a parent, print -1. s is ID of its sibling. If the node does not have a sibling, print -1. deg, dep and h are the number of children, depth and height of the node respectively. type is a type of nodes represented by a string (root, internal node or leaf. If the root can be considered as a leaf or an internal node, print root. Please follow the format presented in a sample output below. Example Input 9 0 1 4 1 2 3 2 -1 -1 3 -1 -1 4 5 8 5 6 7 6 -1 -1 7 -1 -1 8 -1 -1 Output node 0: parent = -1, sibling = -1, degree = 2, depth = 0, height = 3, root node 1: parent = 0, sibling = 4, degree = 2, depth = 1, height = 1, internal node node 2: parent = 1, sibling = 3, degree = 0, depth = 2, height = 0, leaf node 3: parent = 1, sibling = 2, degree = 0, depth = 2, height = 0, leaf node 4: parent = 0, sibling = 1, degree = 2, depth = 1, height = 2, internal node node 5: parent = 4, sibling = 8, degree = 2, depth = 2, height = 1, internal node node 6: parent = 5, sibling = 7, degree = 0, depth = 3, height = 0, leaf node 7: parent = 5, sibling = 6, degree = 0, depth = 3, height = 0, leaf node 8: parent = 4, sibling = 5, degree = 0, depth = 2, height = 0, leaf Submitted Solution: ``` def q(a,k): d[a]=k for b in t[a]: if'-1'!=b:q(b,k+1) def n(a,k): h[a]=max(h[a],k)if a in h else k if'-1'!=p[a]:n(p[a],k+1) t,p,s,d,h={},{},{},{},{} for _ in[0]*int(input()): x,y,z=input().split() t[x]=set([y,z])-{-1} p[y]=p[z]=x s[y],s[z]=z,y r=(set(t)-set(p)).pop() p[r]=s[r]='-1' q(r,0) for i in t: if not t[i]:n(i,0) for i in map(str,sorted(map(int,t))): print(f"node {i}: parent = {p[i]}, sibling = {s[i]}, degree = {len(t[i])}, depth = {d[i]}, height = {h[i]}, {'root'if d[i]==0else'internal node'if t[i]else'leaf'}") ```
instruction
0
51,290
13
102,580
No
output
1
51,290
13
102,581
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A rooted binary tree is a tree with a root node in which every node has at most two children. Your task is to write a program which reads a rooted binary tree T and prints the following information for each node u of T: * node ID of u * parent of u * sibling of u * the number of children of u * depth of u * height of u * node type (root, internal node or leaf) If two nodes have the same parent, they are siblings. Here, if u and v have the same parent, we say u is a sibling of v (vice versa). The height of a node in a tree is the number of edges on the longest simple downward path from the node to a leaf. Here, the given binary tree consists of n nodes and evey node has a unique ID from 0 to n-1. Constraints * 1 ≤ n ≤ 25 Input The first line of the input includes an integer n, the number of nodes of the tree. In the next n lines, the information of each node is given in the following format: id left right id is the node ID, left is ID of the left child and right is ID of the right child. If the node does not have the left (right) child, the left(right) is indicated by -1. Output Print the information of each node in the following format: node id: parent = p, sibling = s, degree = deg, depth = dep, height = h, type p is ID of its parent. If the node does not have a parent, print -1. s is ID of its sibling. If the node does not have a sibling, print -1. deg, dep and h are the number of children, depth and height of the node respectively. type is a type of nodes represented by a string (root, internal node or leaf. If the root can be considered as a leaf or an internal node, print root. Please follow the format presented in a sample output below. Example Input 9 0 1 4 1 2 3 2 -1 -1 3 -1 -1 4 5 8 5 6 7 6 -1 -1 7 -1 -1 8 -1 -1 Output node 0: parent = -1, sibling = -1, degree = 2, depth = 0, height = 3, root node 1: parent = 0, sibling = 4, degree = 2, depth = 1, height = 1, internal node node 2: parent = 1, sibling = 3, degree = 0, depth = 2, height = 0, leaf node 3: parent = 1, sibling = 2, degree = 0, depth = 2, height = 0, leaf node 4: parent = 0, sibling = 1, degree = 2, depth = 1, height = 2, internal node node 5: parent = 4, sibling = 8, degree = 2, depth = 2, height = 1, internal node node 6: parent = 5, sibling = 7, degree = 0, depth = 3, height = 0, leaf node 7: parent = 5, sibling = 6, degree = 0, depth = 3, height = 0, leaf node 8: parent = 4, sibling = 5, degree = 0, depth = 2, height = 0, leaf Submitted Solution: ``` class Node: def __init__(self, parent=-1, left=-1, right=-1): self.parent = parent self.left = left self.right = right n = int(input()) binary_tree = [Node() for i in range(n)] h, d = [0 for j in range(n)], [0 for k in range(n)] def set_height(u): h1 = h2 = 0 if binary_tree[u].right != -1: h1 = set_height(binary_tree[u].right) + 1 if binary_tree[u].left != -1: h2 = set_height(binary_tree[u].left) + 1 h[u] = max(h1, h2) return h[u] def set_depth(u, dep): d[u] = dep if binary_tree[u].right != -1: set_depth(binary_tree[u].right, dep+1) if binary_tree[u].left != -1: set_depth(binary_tree[u].left, dep+1) return d[u] def set_sibling(u): if binary_tree[binary_tree[u].parent].left != u: return binary_tree[binary_tree[u].parent].left else: return binary_tree[binary_tree[u].parent].right def set_degree(u): cnt = 0 if binary_tree[u].left != -1: cnt += 1 if binary_tree[u].right != -1: cnt += 1 return cnt def set_type(u): if binary_tree[u].parent == -1: return "root" elif binary_tree[u].left == -1 and binary_tree[u].right == -1: return "leaf" else: return "internal node" def main(): for i in range(n): idx, left, right = map(int, input().split()) binary_tree[idx].left = left binary_tree[idx].right = right if left != -1: binary_tree[left].parent = idx if right != -1: binary_tree[right].parent = idx # 根の探索 root_idx = 0 for i in range(n): if binary_tree[i].parent == -1: root_idx = i break # 各ノードの高さを求める set_height(root_idx) # 各ノードの深さを求める set_depth(0, 0) for i in range(n): print("node {}: parent = {}, sibling = {}, degree = {}, depth = {}, " "height = {}, type = {}".format(i, binary_tree[i].parent, set_sibling(i), set_degree(i), d[i], h[i], set_type(i))) if __name__ == '__main__': main() ```
instruction
0
51,291
13
102,582
No
output
1
51,291
13
102,583
Provide tags and a correct Python 3 solution for this coding contest problem. Misha walked through the snowy forest and he was so fascinated by the trees to decide to draw his own tree! Misha would like to construct a rooted tree with n vertices, indexed from 1 to n, where the root has index 1. Every other vertex has a parent p_i, and i is called a child of vertex p_i. Vertex u belongs to the subtree of vertex v iff v is reachable from u while iterating over the parents (u, p_{u}, p_{p_{u}}, ...). Clearly, v belongs to its own subtree, and the number of vertices in the subtree is called the size of the subtree. Misha is only interested in trees where every vertex belongs to the subtree of vertex 1. Below there is a tree with 6 vertices. The subtree of vertex 2 contains vertices 2, 3, 4, 5. Hence the size of its subtree is 4. <image> The branching coefficient of the tree is defined as the maximum number of children in any vertex. For example, for the tree above the branching coefficient equals 2. Your task is to construct a tree with n vertices such that the sum of the subtree sizes for all vertices equals s, and the branching coefficient is minimum possible. Input The only input line contains two integers n and s — the number of vertices in the tree and the desired sum of the subtree sizes (2 ≤ n ≤ 10^5; 1 ≤ s ≤ 10^{10}). Output If the required tree does not exist, output «No». Otherwise output «Yes» on the first line, and in the next one output integers p_2, p_3, ..., p_n, where p_i denotes the parent of vertex i. Examples Input 3 5 Output Yes 1 1 Input 4 42 Output No Input 6 15 Output Yes 1 2 3 1 5 Note Below one can find one of the possible solutions for the first sample case. The sum of subtree sizes equals 3 + 1 + 1 = 5, and the branching coefficient equals 2. <image> Below one can find one of the possible solutions for the third sample case. The sum of subtree sizes equals 6 + 3 + 2 + 1 + 2 + 1 = 15, and the branching coefficient equals 2. <image>
instruction
0
51,336
13
102,672
Tags: binary search, constructive algorithms, dfs and similar, graphs, greedy, trees Correct Solution: ``` import sys n,s=map(int,input().split()) if 2*s>n*(n+1) or s<2*n-1: print('NO') sys.exit() for i in range(n,-1,-1): if i==0: branch=1 break tmp=0 tmpn=n j=1 while tmpn-i**(j-1)>=0: tmp+=j*(i**(j-1)) tmpn-=i**(j-1) j+=1 tmp+=j*(tmpn) if tmp>s: branch=i+1 break tmp=0 tmpn=n j=1 i=branch dic={} while tmpn-i**(j-1)>=0: tmp+=j*(i**(j-1)) dic[j]=(i**(j-1)) tmpn-=i**(j-1) j+=1 tmp+=j*(tmpn) dic[j]=tmpn maxi=j while tmp<s: for j in range(maxi,-1,-1): while dic[j]>1: if s-tmp+j<=maxi: dic[j]-=1 dic[s-tmp+j]+=1 tmp=s else: dic[j]-=1 dic[maxi+1]=1 tmp+=maxi+1-j maxi+=1 if tmp==s: break if tmp==s: break b=[] for i in dic: for j in range(dic[i]): b.append(i) b.sort() print('YES') children=[0]*n ans=[-1]*n curr=0 pointer=0 for i in range(1,n): while b[i]>b[curr]+1: curr+=1 ans[i]=curr children[curr]+=1 if children[curr]==branch: curr+=1 finans=[] for i in range(1,n): finans.append(ans[i]+1) print(' '.join(map(str,finans))) ```
output
1
51,336
13
102,673
Provide tags and a correct Python 3 solution for this coding contest problem. Misha walked through the snowy forest and he was so fascinated by the trees to decide to draw his own tree! Misha would like to construct a rooted tree with n vertices, indexed from 1 to n, where the root has index 1. Every other vertex has a parent p_i, and i is called a child of vertex p_i. Vertex u belongs to the subtree of vertex v iff v is reachable from u while iterating over the parents (u, p_{u}, p_{p_{u}}, ...). Clearly, v belongs to its own subtree, and the number of vertices in the subtree is called the size of the subtree. Misha is only interested in trees where every vertex belongs to the subtree of vertex 1. Below there is a tree with 6 vertices. The subtree of vertex 2 contains vertices 2, 3, 4, 5. Hence the size of its subtree is 4. <image> The branching coefficient of the tree is defined as the maximum number of children in any vertex. For example, for the tree above the branching coefficient equals 2. Your task is to construct a tree with n vertices such that the sum of the subtree sizes for all vertices equals s, and the branching coefficient is minimum possible. Input The only input line contains two integers n and s — the number of vertices in the tree and the desired sum of the subtree sizes (2 ≤ n ≤ 10^5; 1 ≤ s ≤ 10^{10}). Output If the required tree does not exist, output «No». Otherwise output «Yes» on the first line, and in the next one output integers p_2, p_3, ..., p_n, where p_i denotes the parent of vertex i. Examples Input 3 5 Output Yes 1 1 Input 4 42 Output No Input 6 15 Output Yes 1 2 3 1 5 Note Below one can find one of the possible solutions for the first sample case. The sum of subtree sizes equals 3 + 1 + 1 = 5, and the branching coefficient equals 2. <image> Below one can find one of the possible solutions for the third sample case. The sum of subtree sizes equals 6 + 3 + 2 + 1 + 2 + 1 = 15, and the branching coefficient equals 2. <image>
instruction
0
51,337
13
102,674
Tags: binary search, constructive algorithms, dfs and similar, graphs, greedy, trees Correct Solution: ``` import math def f(n,k): if k==1: return (n*(n+1))//2 a=math.floor(math.log(n,k)) b=sum(k**i for i in range(a+1)) c=sum((i+1)*k**i for i in range(a+1)) if n<b: return c-(b-n)*(a+1) else: return c+(n-b)*(a+2) n,s=map(int,input().split()) if s==(n*(n+1))//2: print("Yes") a=[str(i+1) for i in range(n-1)] print(" ".join(a)) elif s>(n*(n+1))//2: print("No") elif s<2*n-1: print("No") else: mini=1 maxi=n-1 curr=1 while True: a,b=f(n,curr),f(n,curr+1) if b>s: mini=curr+1 curr=math.ceil((curr+maxi)/2) elif a<=s: maxi=curr-1 curr=(curr+mini)//2 else: opt=curr+1 break depths=[0,1]+[0]*(n-1) ins=1 ind=2 while True: a=min(opt**(ind-1),n-ins) depths[ind]=a ind+=1 ins+=a if ins==n: break left=s-b far=ind-1 bulk=ind-1 if depths[bulk]==1: bulk-=1 while left>0: if far+1-bulk<=left: far+=1 left-=far-bulk depths[far]+=1 depths[bulk]-=1 if depths[bulk]==1: bulk-=1 else: depths[bulk]-=1 depths[bulk+left]+=1 left=0 verts=[None]*far sumi=0 for i in range(far): verts[i]=list(range(sumi+1,sumi+1+depths[i+1])) sumi+=depths[i+1] out="" for i in range(1,far): for j in range(len(verts[i])): out+=str(verts[i-1][j//opt])+" " print("Yes") print(out) ```
output
1
51,337
13
102,675
Provide tags and a correct Python 3 solution for this coding contest problem. Misha walked through the snowy forest and he was so fascinated by the trees to decide to draw his own tree! Misha would like to construct a rooted tree with n vertices, indexed from 1 to n, where the root has index 1. Every other vertex has a parent p_i, and i is called a child of vertex p_i. Vertex u belongs to the subtree of vertex v iff v is reachable from u while iterating over the parents (u, p_{u}, p_{p_{u}}, ...). Clearly, v belongs to its own subtree, and the number of vertices in the subtree is called the size of the subtree. Misha is only interested in trees where every vertex belongs to the subtree of vertex 1. Below there is a tree with 6 vertices. The subtree of vertex 2 contains vertices 2, 3, 4, 5. Hence the size of its subtree is 4. <image> The branching coefficient of the tree is defined as the maximum number of children in any vertex. For example, for the tree above the branching coefficient equals 2. Your task is to construct a tree with n vertices such that the sum of the subtree sizes for all vertices equals s, and the branching coefficient is minimum possible. Input The only input line contains two integers n and s — the number of vertices in the tree and the desired sum of the subtree sizes (2 ≤ n ≤ 10^5; 1 ≤ s ≤ 10^{10}). Output If the required tree does not exist, output «No». Otherwise output «Yes» on the first line, and in the next one output integers p_2, p_3, ..., p_n, where p_i denotes the parent of vertex i. Examples Input 3 5 Output Yes 1 1 Input 4 42 Output No Input 6 15 Output Yes 1 2 3 1 5 Note Below one can find one of the possible solutions for the first sample case. The sum of subtree sizes equals 3 + 1 + 1 = 5, and the branching coefficient equals 2. <image> Below one can find one of the possible solutions for the third sample case. The sum of subtree sizes equals 6 + 3 + 2 + 1 + 2 + 1 = 15, and the branching coefficient equals 2. <image>
instruction
0
51,338
13
102,676
Tags: binary search, constructive algorithms, dfs and similar, graphs, greedy, trees Correct Solution: ``` import math EPS = 1e-6 hhh = None def solve(): n, M = [int(x) for x in input().split()] if out_of_solution_bounds(n, M): print('No') return b = find_optimal_b(n, M) heights = fast_find_optimal_height_distribution(n, M, b) parents = build_tree(n, b, heights) print('Yes') print(*parents[1:]) def out_of_solution_bounds(n, M): return M < 2*n - 1 or (n * (n+1)) // 2 < M def find_optimal_b(n, M): begin = 1 end = n while begin != end: mid = (begin + end) // 2 if get_min_H_given_b(n, mid) <= M: end = mid else: begin = mid + 1 b = end return b def get_min_H_given_b(n, b): if b == 1: return (n*(n+1)) // 2 m = math.floor(math.log((b-1)*n+1) / math.log(b) + EPS) nl = round((b**m - 1) / (b - 1)) return (m*b**(m+1) - (m+1)*b**m + 1) // (b - 1)**2 + (m+1) * (n - nl) def fast_find_optimal_height_distribution(n, M, b): begin = 0 end = n+1 H_fn = lambda L : (L*(L+1))//2 + get_min_H_given_b(n - L, b) + (L > 0)*(n - L) while begin != end: mid = (begin + end) // 2 if H_fn(mid) <= M: begin = mid + 1 else: end = mid L = begin - 1 if L == n: return [1 for _ in range(n)] unif_branch_h = uniform_height_distribution(n - L, b) if L == 0: h = unif_branch_h else: h = [int(i < L) for i in range(n)] for i, x in enumerate(unif_branch_h, 1): h[i] += x return locally_increase_H(h, M, b) def uniform_height_distribution(n, b): h = [0 for _ in range(n)] h[0] = 1 i = 0 to_fill = n-1 while to_fill > 0: i += 1 h[i] = min(b*h[i-1], to_fill) to_fill -= h[i] return h def locally_increase_H(h, M, b): i = 1 while not (b * (h[i-1]) >= (h[i] - 1) and b * (h[i] - 1) >= (h[i+1] + 1)): i += 1 H = sum(i*x for i, x in enumerate(h, 1)) while H < M: if b * (h[i-1] - 1) >= (h[i] + 1): i -= 1 else: while not b * (h[i] - 1) >= (h[i+1] + 1): i += 1 h[i] -= 1 h[i+1] += 1 H += 1 return h def build_tree(n, b, h): p = [None for _ in range(n)] p[0] = 1 i = 1 j = 0 for k in range(1, n): if j == h[i]: i += 1 j = 0 p[k] = k - j - h[i-1] + (j // b) + 1 j += 1 return p if __name__ == '__main__': solve() ```
output
1
51,338
13
102,677
Provide tags and a correct Python 3 solution for this coding contest problem. Misha walked through the snowy forest and he was so fascinated by the trees to decide to draw his own tree! Misha would like to construct a rooted tree with n vertices, indexed from 1 to n, where the root has index 1. Every other vertex has a parent p_i, and i is called a child of vertex p_i. Vertex u belongs to the subtree of vertex v iff v is reachable from u while iterating over the parents (u, p_{u}, p_{p_{u}}, ...). Clearly, v belongs to its own subtree, and the number of vertices in the subtree is called the size of the subtree. Misha is only interested in trees where every vertex belongs to the subtree of vertex 1. Below there is a tree with 6 vertices. The subtree of vertex 2 contains vertices 2, 3, 4, 5. Hence the size of its subtree is 4. <image> The branching coefficient of the tree is defined as the maximum number of children in any vertex. For example, for the tree above the branching coefficient equals 2. Your task is to construct a tree with n vertices such that the sum of the subtree sizes for all vertices equals s, and the branching coefficient is minimum possible. Input The only input line contains two integers n and s — the number of vertices in the tree and the desired sum of the subtree sizes (2 ≤ n ≤ 10^5; 1 ≤ s ≤ 10^{10}). Output If the required tree does not exist, output «No». Otherwise output «Yes» on the first line, and in the next one output integers p_2, p_3, ..., p_n, where p_i denotes the parent of vertex i. Examples Input 3 5 Output Yes 1 1 Input 4 42 Output No Input 6 15 Output Yes 1 2 3 1 5 Note Below one can find one of the possible solutions for the first sample case. The sum of subtree sizes equals 3 + 1 + 1 = 5, and the branching coefficient equals 2. <image> Below one can find one of the possible solutions for the third sample case. The sum of subtree sizes equals 6 + 3 + 2 + 1 + 2 + 1 = 15, and the branching coefficient equals 2. <image>
instruction
0
51,339
13
102,678
Tags: binary search, constructive algorithms, dfs and similar, graphs, greedy, trees Correct Solution: ``` def clc(mid): sm , i , cp = 0 , 1 , n cur = 1 while(cp + 1 > cur): sm = sm + i * cur i+= 1 cp -= cur cur = cur * mid return sm + i * cp n , s = map(int,input().split()) sm = n * (n + 1) // 2 dp = [0] * 100005 x = [0] * 100005 y = [0] * 100005 x[0] = 1 if s + 1 < 2 * n: print("No") exit() if s > sm: print("No") exit() else: print("Yes") l = 0 r = n while r - l > 1: mid = (r + l) // 2 if(clc(mid) > s): l = mid else: r = mid i = 2 while( i < n + 1): y[i] = i + r y[i] -= 2 y[i] = y[i] // r x[i] = x[y[i]] + 1 if(dp[x[i]] == 0): dp[x[i]] = i i = i + 1 mx = x[n] ip = n s = s - clc(r) while(s != 0): if(x[ip] != x[ip - 1]): ip = ip - 1; if(s > mx - x[ip]): y[ip] = dp[mx] mx = mx + 1 s -= mx - x[ip] x[ip] = mx dp[mx] = ip else: y[ip] = dp[s + x[ip] - 1] s = 0 ip = ip - 1 i = 2 while(i < n + 1): print(y[i]) i = i + 1 ```
output
1
51,339
13
102,679
Provide tags and a correct Python 3 solution for this coding contest problem. Misha walked through the snowy forest and he was so fascinated by the trees to decide to draw his own tree! Misha would like to construct a rooted tree with n vertices, indexed from 1 to n, where the root has index 1. Every other vertex has a parent p_i, and i is called a child of vertex p_i. Vertex u belongs to the subtree of vertex v iff v is reachable from u while iterating over the parents (u, p_{u}, p_{p_{u}}, ...). Clearly, v belongs to its own subtree, and the number of vertices in the subtree is called the size of the subtree. Misha is only interested in trees where every vertex belongs to the subtree of vertex 1. Below there is a tree with 6 vertices. The subtree of vertex 2 contains vertices 2, 3, 4, 5. Hence the size of its subtree is 4. <image> The branching coefficient of the tree is defined as the maximum number of children in any vertex. For example, for the tree above the branching coefficient equals 2. Your task is to construct a tree with n vertices such that the sum of the subtree sizes for all vertices equals s, and the branching coefficient is minimum possible. Input The only input line contains two integers n and s — the number of vertices in the tree and the desired sum of the subtree sizes (2 ≤ n ≤ 10^5; 1 ≤ s ≤ 10^{10}). Output If the required tree does not exist, output «No». Otherwise output «Yes» on the first line, and in the next one output integers p_2, p_3, ..., p_n, where p_i denotes the parent of vertex i. Examples Input 3 5 Output Yes 1 1 Input 4 42 Output No Input 6 15 Output Yes 1 2 3 1 5 Note Below one can find one of the possible solutions for the first sample case. The sum of subtree sizes equals 3 + 1 + 1 = 5, and the branching coefficient equals 2. <image> Below one can find one of the possible solutions for the third sample case. The sum of subtree sizes equals 6 + 3 + 2 + 1 + 2 + 1 = 15, and the branching coefficient equals 2. <image>
instruction
0
51,340
13
102,680
Tags: binary search, constructive algorithms, dfs and similar, graphs, greedy, trees Correct Solution: ``` def good(max_branch, s, n): nodes = 0 can = 1 lowest_s = 0 depth = 1 while(nodes < n): added = min(n - nodes, can) lowest_s += added * depth nodes += added can *= max_branch depth += 1 return lowest_s <= s n, s = map(int, input().split()) if s < 2 * n - 1 or s * 2 > n * (n + 1): print('No') else: lo, hi = 1, n while lo < hi: mid = (lo + hi) >> 1 if good(mid, s, n) == False: lo = mid + 1 else: hi = mid max_branch = lo level_size = [1] * (n + 1) node_level = [i for i in range(n + 1)] cur_node = n cur_level = 1 cur_sum = n * (n + 1) // 2 can = 1 while cur_sum > s: if level_size[cur_level] == can: cur_level += 1 can *= max_branch if cur_sum - (cur_node - cur_level) < s: cur_level = cur_node - (cur_sum - s) node_level[cur_node] = cur_level level_size[cur_level] += 1 cur_sum -= cur_node - cur_level cur_node -= 1 #print(cur_sum) #print(node_level) node_list = [[] for _ in range(n + 1)] for i in range(1, n + 1): node_list[node_level[i]].append(i) pre = 0 children = [0] * (n + 1) parent = [-1] * (n + 1) seen_nodes = 1 for level in range(2, n + 1): idx = 0 if not node_list[level - 1]: assert seen_nodes == n break cur_father = node_list[level - 1][0] for node in node_list[level]: if children[cur_father] == max_branch: idx += 1 cur_father = node_list[level - 1][idx] children[cur_father] += 1 parent[node] = cur_father seen_nodes += 1 print('Yes') print(*parent[2:]) ```
output
1
51,340
13
102,681
Provide tags and a correct Python 3 solution for this coding contest problem. Misha walked through the snowy forest and he was so fascinated by the trees to decide to draw his own tree! Misha would like to construct a rooted tree with n vertices, indexed from 1 to n, where the root has index 1. Every other vertex has a parent p_i, and i is called a child of vertex p_i. Vertex u belongs to the subtree of vertex v iff v is reachable from u while iterating over the parents (u, p_{u}, p_{p_{u}}, ...). Clearly, v belongs to its own subtree, and the number of vertices in the subtree is called the size of the subtree. Misha is only interested in trees where every vertex belongs to the subtree of vertex 1. Below there is a tree with 6 vertices. The subtree of vertex 2 contains vertices 2, 3, 4, 5. Hence the size of its subtree is 4. <image> The branching coefficient of the tree is defined as the maximum number of children in any vertex. For example, for the tree above the branching coefficient equals 2. Your task is to construct a tree with n vertices such that the sum of the subtree sizes for all vertices equals s, and the branching coefficient is minimum possible. Input The only input line contains two integers n and s — the number of vertices in the tree and the desired sum of the subtree sizes (2 ≤ n ≤ 10^5; 1 ≤ s ≤ 10^{10}). Output If the required tree does not exist, output «No». Otherwise output «Yes» on the first line, and in the next one output integers p_2, p_3, ..., p_n, where p_i denotes the parent of vertex i. Examples Input 3 5 Output Yes 1 1 Input 4 42 Output No Input 6 15 Output Yes 1 2 3 1 5 Note Below one can find one of the possible solutions for the first sample case. The sum of subtree sizes equals 3 + 1 + 1 = 5, and the branching coefficient equals 2. <image> Below one can find one of the possible solutions for the third sample case. The sum of subtree sizes equals 6 + 3 + 2 + 1 + 2 + 1 = 15, and the branching coefficient equals 2. <image>
instruction
0
51,341
13
102,682
Tags: binary search, constructive algorithms, dfs and similar, graphs, greedy, trees Correct Solution: ``` n, s = map(int, input().split()) if not 2*n - 1 <= s <= n * (n+1) // 2: print('No') exit() print('Yes') def ok(d): dep, cur, sum, m = 2, 1, 1, 0 while cur + m < n: m += cur cur = min(n - m, cur * d) sum += cur * dep dep += 1 return sum <= s l, r = 1, n while l < r: mid = (l+r) // 2 if ok(mid): r = mid else: l = mid + 1 a, me = [l-1] * (n+1), [_ for _ in range(n+1)] sum, low = n * (n+1) // 2, 2 while n > low and sum > s: dest = min(sum-s, n-low) sum -= dest me[n] -= dest a[me[n]+1] += l a[me[n]] -= 1 if not a[low]: low += 1 n -= 1 me, l, dg = sorted(me[1:]), 0, 0 for i in me[1:]: while me[l] < i-1 or dg == r: dg = 0 l += 1 print(l+1, end=' ') dg += 1 ```
output
1
51,341
13
102,683
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Misha walked through the snowy forest and he was so fascinated by the trees to decide to draw his own tree! Misha would like to construct a rooted tree with n vertices, indexed from 1 to n, where the root has index 1. Every other vertex has a parent p_i, and i is called a child of vertex p_i. Vertex u belongs to the subtree of vertex v iff v is reachable from u while iterating over the parents (u, p_{u}, p_{p_{u}}, ...). Clearly, v belongs to its own subtree, and the number of vertices in the subtree is called the size of the subtree. Misha is only interested in trees where every vertex belongs to the subtree of vertex 1. Below there is a tree with 6 vertices. The subtree of vertex 2 contains vertices 2, 3, 4, 5. Hence the size of its subtree is 4. <image> The branching coefficient of the tree is defined as the maximum number of children in any vertex. For example, for the tree above the branching coefficient equals 2. Your task is to construct a tree with n vertices such that the sum of the subtree sizes for all vertices equals s, and the branching coefficient is minimum possible. Input The only input line contains two integers n and s — the number of vertices in the tree and the desired sum of the subtree sizes (2 ≤ n ≤ 10^5; 1 ≤ s ≤ 10^{10}). Output If the required tree does not exist, output «No». Otherwise output «Yes» on the first line, and in the next one output integers p_2, p_3, ..., p_n, where p_i denotes the parent of vertex i. Examples Input 3 5 Output Yes 1 1 Input 4 42 Output No Input 6 15 Output Yes 1 2 3 1 5 Note Below one can find one of the possible solutions for the first sample case. The sum of subtree sizes equals 3 + 1 + 1 = 5, and the branching coefficient equals 2. <image> Below one can find one of the possible solutions for the third sample case. The sum of subtree sizes equals 6 + 3 + 2 + 1 + 2 + 1 = 15, and the branching coefficient equals 2. <image> Submitted Solution: ``` def clc(mid): sm , i , cp = 0 , 1 , n cur = 1 while(cp + 1 > cur): sm = sm + i * cur i+= 1 cp -= cur cur = cur * mid return sm + i * cp n , s = map(int,input().split()) sm = n * (n + 1) // 2 dp = [0] * 100005 x = [0] * 100005 y = [0] * 100005 x[0] = 1 if s + 1 < 2 * n: print("No") exit() if s > sm: print("No") exit() else: print("Yes") l = 0 r = n while r - l > 1: mid = (r + l) // 2 if(clc(mid) > s): l = mid else: r = mid i = 2 while( i < n + 1): y[i] = i + r y[i] -= 2 y[i] = y[i] // r x[i] = x[y[i]] + 1 if(dp[x[i]] == 0): dp[x[i]] = i i = i + 1 mx = x[n] ip = n s = s - clc(r) while(s != 0): if(x[ip] != x[ip - 1]): ip = ip - 1; if(s > mx - x[ip]): y[ip] = dp[mx] mx = mx + 1 s -= mx - x[ip] x[ip] = mx dp[mx] = ip else: x[ip] = dp[s + x[ip] - 1] s = 0 ip = ip - 1 i = 2 while(i < n + 1): print(y[i]) i = i + 1 ```
instruction
0
51,342
13
102,684
No
output
1
51,342
13
102,685
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Misha walked through the snowy forest and he was so fascinated by the trees to decide to draw his own tree! Misha would like to construct a rooted tree with n vertices, indexed from 1 to n, where the root has index 1. Every other vertex has a parent p_i, and i is called a child of vertex p_i. Vertex u belongs to the subtree of vertex v iff v is reachable from u while iterating over the parents (u, p_{u}, p_{p_{u}}, ...). Clearly, v belongs to its own subtree, and the number of vertices in the subtree is called the size of the subtree. Misha is only interested in trees where every vertex belongs to the subtree of vertex 1. Below there is a tree with 6 vertices. The subtree of vertex 2 contains vertices 2, 3, 4, 5. Hence the size of its subtree is 4. <image> The branching coefficient of the tree is defined as the maximum number of children in any vertex. For example, for the tree above the branching coefficient equals 2. Your task is to construct a tree with n vertices such that the sum of the subtree sizes for all vertices equals s, and the branching coefficient is minimum possible. Input The only input line contains two integers n and s — the number of vertices in the tree and the desired sum of the subtree sizes (2 ≤ n ≤ 10^5; 1 ≤ s ≤ 10^{10}). Output If the required tree does not exist, output «No». Otherwise output «Yes» on the first line, and in the next one output integers p_2, p_3, ..., p_n, where p_i denotes the parent of vertex i. Examples Input 3 5 Output Yes 1 1 Input 4 42 Output No Input 6 15 Output Yes 1 2 3 1 5 Note Below one can find one of the possible solutions for the first sample case. The sum of subtree sizes equals 3 + 1 + 1 = 5, and the branching coefficient equals 2. <image> Below one can find one of the possible solutions for the third sample case. The sum of subtree sizes equals 6 + 3 + 2 + 1 + 2 + 1 = 15, and the branching coefficient equals 2. <image> Submitted Solution: ``` import math EPS = 1e-6 def solve(): n, M = [int(x) for x in input().split()] if out_of_solution_bounds(n, M): print('No') return b = find_optimal_b(n, M) heights = fast_find_optimal_height_distribution(n, M, b) parents = build_tree(n, b, heights) print('Yes') print(*parents[1:]) def out_of_solution_bounds(n, M): return M < 2*n - 1 or (n * (n+1)) // 2 < M def find_optimal_b(n, M): begin = 1 end = n while begin != end: mid = (begin + end) // 2 if get_min_H_given_b(n, mid) <= M: end = mid else: begin = mid + 1 b = end return b def get_min_H_given_b(n, b): if b == 1: return (n*(n+1)) // 2 m = math.floor(math.log((b-1)*n+1) / math.log(b) + EPS) nl = round((b**m - 1) / (b - 1)) return (m*b**(m+1) - (m+1)*b**m + 1) // (b - 1)**2 + (m+1) * (n - nl) def fast_find_optimal_height_distribution(n, M, b): begin = 0 end = n+1 H_fn = lambda L : (L*(L+1))//2 + get_min_H_given_b(n - L, b) + (L > 0)*(n - L) while begin != end: mid = (begin + end) // 2 if H_fn(mid) <= M: begin = mid + 1 else: end = mid L = begin - 1 if L == n: return [1 for _ in range(n)] unif_branch_h = uniform_height_distribution(n - L, b) if L == 0: h = unif_branch_h else: h = [(i < L) for i in range(n)] for i, x in enumerate(unif_branch_h, 1): h[i] += x return locally_increase_H(h, M, b) def uniform_height_distribution(n, b): h = [0 for _ in range(n)] h[0] = 1 i = 0 to_fill = n-1 while to_fill > 0: i += 1 h[i] = min(b*h[i-1], to_fill) to_fill -= h[i] return h def locally_increase_H(h, M, b): i = 0 while not b * (h[i] - 1) >= (h[i+1] + 1): i += 1 H = sum(i*x for i, x in enumerate(h, 1)) while H < M: if b * (h[i-1] - 1) >= (h[i] + 1): i -= 1 elif not b * (h[i] - 1) >= (h[i+1] + 1): i += 1 h[i] -= 1 h[i+1] += 1 H += 1 return h def build_tree(n, b, h): nh = [[None for _ in range(x)] for x in h] p = [None for _ in range(n)] p[0] = 1 nh[0] = 0 i = 1 j = 0 for k in range(1, n): if j == h[i]: i += 1 j = 0 p[k] = k - j - h[i-1] + (j // b) + 1 j += 1 return p if __name__ == '__main__': solve() ```
instruction
0
51,343
13
102,686
No
output
1
51,343
13
102,687
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Misha walked through the snowy forest and he was so fascinated by the trees to decide to draw his own tree! Misha would like to construct a rooted tree with n vertices, indexed from 1 to n, where the root has index 1. Every other vertex has a parent p_i, and i is called a child of vertex p_i. Vertex u belongs to the subtree of vertex v iff v is reachable from u while iterating over the parents (u, p_{u}, p_{p_{u}}, ...). Clearly, v belongs to its own subtree, and the number of vertices in the subtree is called the size of the subtree. Misha is only interested in trees where every vertex belongs to the subtree of vertex 1. Below there is a tree with 6 vertices. The subtree of vertex 2 contains vertices 2, 3, 4, 5. Hence the size of its subtree is 4. <image> The branching coefficient of the tree is defined as the maximum number of children in any vertex. For example, for the tree above the branching coefficient equals 2. Your task is to construct a tree with n vertices such that the sum of the subtree sizes for all vertices equals s, and the branching coefficient is minimum possible. Input The only input line contains two integers n and s — the number of vertices in the tree and the desired sum of the subtree sizes (2 ≤ n ≤ 10^5; 1 ≤ s ≤ 10^{10}). Output If the required tree does not exist, output «No». Otherwise output «Yes» on the first line, and in the next one output integers p_2, p_3, ..., p_n, where p_i denotes the parent of vertex i. Examples Input 3 5 Output Yes 1 1 Input 4 42 Output No Input 6 15 Output Yes 1 2 3 1 5 Note Below one can find one of the possible solutions for the first sample case. The sum of subtree sizes equals 3 + 1 + 1 = 5, and the branching coefficient equals 2. <image> Below one can find one of the possible solutions for the third sample case. The sum of subtree sizes equals 6 + 3 + 2 + 1 + 2 + 1 = 15, and the branching coefficient equals 2. <image> Submitted Solution: ``` n, s = map(int, input().split()) parent = [i - 1 for i in range(n + 1)] if s < 2 * n - 1 or s * 2 > n * (n + 1): print('No') else: cur = (n * (n + 1)) // 2 offset = 2 while cur > s: can = n - offset need = cur - s jump = min(can, need) new_root = n - jump + 1 parent[new_root] = parent[parent[new_root]] cur -= jump offset = new_root print('Yes') print(*parent[2:]) ```
instruction
0
51,344
13
102,688
No
output
1
51,344
13
102,689
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Misha walked through the snowy forest and he was so fascinated by the trees to decide to draw his own tree! Misha would like to construct a rooted tree with n vertices, indexed from 1 to n, where the root has index 1. Every other vertex has a parent p_i, and i is called a child of vertex p_i. Vertex u belongs to the subtree of vertex v iff v is reachable from u while iterating over the parents (u, p_{u}, p_{p_{u}}, ...). Clearly, v belongs to its own subtree, and the number of vertices in the subtree is called the size of the subtree. Misha is only interested in trees where every vertex belongs to the subtree of vertex 1. Below there is a tree with 6 vertices. The subtree of vertex 2 contains vertices 2, 3, 4, 5. Hence the size of its subtree is 4. <image> The branching coefficient of the tree is defined as the maximum number of children in any vertex. For example, for the tree above the branching coefficient equals 2. Your task is to construct a tree with n vertices such that the sum of the subtree sizes for all vertices equals s, and the branching coefficient is minimum possible. Input The only input line contains two integers n and s — the number of vertices in the tree and the desired sum of the subtree sizes (2 ≤ n ≤ 10^5; 1 ≤ s ≤ 10^{10}). Output If the required tree does not exist, output «No». Otherwise output «Yes» on the first line, and in the next one output integers p_2, p_3, ..., p_n, where p_i denotes the parent of vertex i. Examples Input 3 5 Output Yes 1 1 Input 4 42 Output No Input 6 15 Output Yes 1 2 3 1 5 Note Below one can find one of the possible solutions for the first sample case. The sum of subtree sizes equals 3 + 1 + 1 = 5, and the branching coefficient equals 2. <image> Below one can find one of the possible solutions for the third sample case. The sum of subtree sizes equals 6 + 3 + 2 + 1 + 2 + 1 = 15, and the branching coefficient equals 2. <image> Submitted Solution: ``` import math EPS = 1e-6 def solve(): n, M = [int(x) for x in input().split()] if out_of_solution_bounds(n, M): print('No') return b = find_optimal_b(n, M) heights = fast_find_optimal_height_distribution(n, M, b) parents = build_tree(n, b, heights) print('Yes') print(*parents[1:]) def out_of_solution_bounds(n, M): return M < 2*n - 1 or (n * (n+1)) // 2 < M def find_optimal_b(n, M): begin = 1 end = n while begin != end: mid = (begin + end) // 2 if get_min_H_given_b(n, mid) <= M: end = mid else: begin = mid + 1 b = end return b def get_min_H_given_b(n, b): if b == 1: return (n*(n+1)) // 2 m = math.floor(math.log((b-1)*n+1) / math.log(b) + EPS) nl = round((b**m - 1) / (b - 1)) return (m*b**(m+1) - (m+1)*b**m + 1) // (b - 1)**2 + (m+1) * (n - nl) def fast_find_optimal_height_distribution(n, M, b): begin = 0 end = n+1 H_fn = lambda L : (L*(L+1))//2 + get_min_H_given_b(n - L, b) + (L > 0)*(n - L) while begin != end: mid = (begin + end) // 2 if H_fn(mid) <= M: begin = mid + 1 else: end = mid L = begin - 1 # print(H_fn(L)) if L == n: return [1 for _ in range(n)] unif_branch_h = uniform_height_distribution(n - L, b) if L == 0: h = unif_branch_h else: h = [int(i < L) for i in range(n)] for i, x in enumerate(unif_branch_h, 1): h[i] += x return locally_increase_H(h, M, b) H = sum(i*x for i, x in enumerate(h, 1)) print(H) h = locally_increase_H(h, M, b) H = sum(i*x for i, x in enumerate(h, 1)) print(H) print(h[:10]) return h def uniform_height_distribution(n, b): h = [0 for _ in range(n)] h[0] = 1 i = 0 to_fill = n-1 while to_fill > 0: i += 1 h[i] = min(b*h[i-1], to_fill) to_fill -= h[i] return h def locally_increase_H(h, M, b): i = 0 while not b * (h[i] - 1) >= (h[i+1] + 1): i += 1 H = sum(i*x for i, x in enumerate(h, 1)) while H < M: if b * (h[i-1] - 1) >= (h[i] + 1): i -= 1 elif not b * (h[i] - 1) >= (h[i+1] + 1): i += 1 h[i] -= 1 h[i+1] += 1 H += 1 return h def build_tree(n, b, h): p = [None for _ in range(n)] p[0] = 1 i = 1 j = 0 for k in range(1, n): if j == h[i]: i += 1 j = 0 p[k] = k - j - h[i-1] + (j // b) + 1 j += 1 return p if __name__ == '__main__': solve() ```
instruction
0
51,345
13
102,690
No
output
1
51,345
13
102,691
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Note that the only difference between the easy and hard version is the constraint on the number of queries. You can make hacks only if all versions of the problem are solved. This is an interactive problem. You are given a tree consisting of n nodes numbered with integers from 1 to n. Ayush and Ashish chose two secret distinct nodes in the tree. You need to find out both the nodes. You can make the following query: * Provide a list of nodes and you will receive a node from that list whose sum of distances to both the hidden nodes is minimal (if there are multiple such nodes in the list, you will receive any one of them). You will also get the sum of distances of that node to the hidden nodes. Recall that a tree is a connected graph without cycles. The distance between two nodes is defined as the number of edges in the simple path between them. More formally, let's define two hidden nodes as s and f. In one query you can provide the set of nodes \\{a_1, a_2, …, a_c\} of the tree. As a result, you will get two numbers a_i and dist(a_i, s) + dist(a_i, f). The node a_i is any node from the provided set, for which the number dist(a_i, s) + dist(a_i, f) is minimal. You can ask no more than 14 queries. Input The first line contains a single integer t (1 ≤ t ≤ 10) — the number of test cases. Please note, how the interaction process is organized. The first line of each test case consists of a single integer n (2 ≤ n ≤ 1000) — the number of nodes in the tree. The next n - 1 lines consist of two integers u, v (1 ≤ u, v ≤ n, u ≠ v) — the edges of the tree. Interaction To ask a query print a single line: * In the beginning print "? c " (without quotes) where c (1 ≤ c ≤ n) denotes the number of nodes being queried, followed by c distinct integers in the range [1, n] — the indices of nodes from the list. For each query, you will receive two integers x, d — the node (among the queried nodes) with the minimum sum of distances to the hidden nodes and the sum of distances from that node to the hidden nodes. If the subset of nodes queried is invalid or you exceeded the number of queries then you will get x = d = -1. In this case, you should terminate the program immediately. When you have guessed the hidden nodes, print a single line "! " (without quotes), followed by two integers in the range [1, n] — the hidden nodes. You can output the hidden nodes in any order. After this, you should read a string. If you guess the nodes correctly, you will receive the string "Correct". In this case, you should continue solving the remaining test cases or terminate the program, if all test cases were solved. Otherwise, you will receive the string "Incorrect". In this case, you should terminate the program immediately. Guessing the hidden nodes does not count towards the number of queries asked. The interactor is not adaptive. The hidden nodes do not change with queries. Do not forget to read the string "Correct" / "Incorrect" after guessing the hidden nodes. You need to solve each test case before receiving the input for the next test case. The limit of 14 queries applies to each test case and not to the entire input. After printing a query do not forget to output the end of the line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use: * fflush(stdout) or cout.flush() in C++; * System.out.flush() in Java; * flush(output) in Pascal; * stdout.flush() in Python; * see the documentation for other languages. Hacks To hack the solution, use the following test format: The first line should contain a single integer t (1 ≤ t ≤ 10) — the number of test cases. The description of the test cases follows. The first line of each test case should contain a single integer n (2 ≤ n ≤ 1000) — the number of nodes in the tree. The second line should contain two distinct integers in the range [1, n] — the hidden nodes. The next n - 1 lines should contain two integers u, v (1 ≤ u, v ≤ n, u ≠ v) — the edges of the tree. Example Input 1 3 1 2 1 3 1 1 2 3 3 1 3 1 Correct Output ? 1 1 ? 1 2 ? 1 3 ? 2 2 3 ! 1 3 Note The tree from the first test is shown below, and the hidden nodes are 1 and 3. <image> Submitted Solution: ``` import sys input = sys.stdin.readline t = int(input()) for _ in range(t): n,k = map(int,input().split()) l = [list(map(int,input().split())) for i in range(k)] le = 1 ri = n while ri > le: m = (ri+le+1)//2 x = [i for i in range(m,ri+1)] print("?",len(x),*x) sys.stdout.flush() if int(input()) == n: le = m else: ri = m-1 x = [] for i in l: if ri in i[1:]: continue for j in i[1:]: x.append(j) x.sort() print("?",len(x),*x) sys.stdout.flush() s = int(input()) ans = [s]*k for i in range(k): if ri in l[i][1:]: ans[i] = n print("!",*ans) sys.stdout.flush() if input() =="Correct": continue else: exit() ```
instruction
0
51,514
13
103,028
No
output
1
51,514
13
103,029
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Note that the only difference between the easy and hard version is the constraint on the number of queries. You can make hacks only if all versions of the problem are solved. This is an interactive problem. You are given a tree consisting of n nodes numbered with integers from 1 to n. Ayush and Ashish chose two secret distinct nodes in the tree. You need to find out both the nodes. You can make the following query: * Provide a list of nodes and you will receive a node from that list whose sum of distances to both the hidden nodes is minimal (if there are multiple such nodes in the list, you will receive any one of them). You will also get the sum of distances of that node to the hidden nodes. Recall that a tree is a connected graph without cycles. The distance between two nodes is defined as the number of edges in the simple path between them. More formally, let's define two hidden nodes as s and f. In one query you can provide the set of nodes \\{a_1, a_2, …, a_c\} of the tree. As a result, you will get two numbers a_i and dist(a_i, s) + dist(a_i, f). The node a_i is any node from the provided set, for which the number dist(a_i, s) + dist(a_i, f) is minimal. You can ask no more than 14 queries. Input The first line contains a single integer t (1 ≤ t ≤ 10) — the number of test cases. Please note, how the interaction process is organized. The first line of each test case consists of a single integer n (2 ≤ n ≤ 1000) — the number of nodes in the tree. The next n - 1 lines consist of two integers u, v (1 ≤ u, v ≤ n, u ≠ v) — the edges of the tree. Interaction To ask a query print a single line: * In the beginning print "? c " (without quotes) where c (1 ≤ c ≤ n) denotes the number of nodes being queried, followed by c distinct integers in the range [1, n] — the indices of nodes from the list. For each query, you will receive two integers x, d — the node (among the queried nodes) with the minimum sum of distances to the hidden nodes and the sum of distances from that node to the hidden nodes. If the subset of nodes queried is invalid or you exceeded the number of queries then you will get x = d = -1. In this case, you should terminate the program immediately. When you have guessed the hidden nodes, print a single line "! " (without quotes), followed by two integers in the range [1, n] — the hidden nodes. You can output the hidden nodes in any order. After this, you should read a string. If you guess the nodes correctly, you will receive the string "Correct". In this case, you should continue solving the remaining test cases or terminate the program, if all test cases were solved. Otherwise, you will receive the string "Incorrect". In this case, you should terminate the program immediately. Guessing the hidden nodes does not count towards the number of queries asked. The interactor is not adaptive. The hidden nodes do not change with queries. Do not forget to read the string "Correct" / "Incorrect" after guessing the hidden nodes. You need to solve each test case before receiving the input for the next test case. The limit of 14 queries applies to each test case and not to the entire input. After printing a query do not forget to output the end of the line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use: * fflush(stdout) or cout.flush() in C++; * System.out.flush() in Java; * flush(output) in Pascal; * stdout.flush() in Python; * see the documentation for other languages. Hacks To hack the solution, use the following test format: The first line should contain a single integer t (1 ≤ t ≤ 10) — the number of test cases. The description of the test cases follows. The first line of each test case should contain a single integer n (2 ≤ n ≤ 1000) — the number of nodes in the tree. The second line should contain two distinct integers in the range [1, n] — the hidden nodes. The next n - 1 lines should contain two integers u, v (1 ≤ u, v ≤ n, u ≠ v) — the edges of the tree. Example Input 1 3 1 2 1 3 1 1 2 3 3 1 3 1 Correct Output ? 1 1 ? 1 2 ? 1 3 ? 2 2 3 ! 1 3 Note The tree from the first test is shown below, and the hidden nodes are 1 and 3. <image> Submitted Solution: ``` from sys import exit from collections import deque from copy import deepcopy def readTree(n): adj = [set() for _ in range(n)] for _ in range(n-1): u,v = map(int, input().split()) adj[u-1].add(v-1) adj[v-1].add(u-1) return adj def nodes_at_depth(n, root, adj, d): q = deque() q.append(root) depth = [-1] * n depth[root] = 0 res = [] parent = [-1] * n while q: v = q.popleft() if depth[v] == d: res.append(v) continue for a in adj[v]: if depth[a] == -1: parent[a] = v depth[a] = depth[v] + 1 q.append(a) return res, parent def query(vv): print('?', len(vv), ' '.join(map(lambda v: str(v+1), vv)), flush=True) v, d = map(int, input().split()) if v == -1: exit() return v-1, d def main(): def solve(): n = int(input()) adj = readTree(n) v, w = solvebody(adj, n, query) print('!', v+1, w+1, flush=True) if input() != "Correct": exit() t = int(input()) for _ in range(t): solve() def solvebody(adj, n, query): # Find a node on the path v, d = query(range(n)) depth = d adjm = deepcopy(adj) while depth > 1: depth = depth// 2 vv, parent = nodes_at_depth(n, v, adjm, depth) if len(vv) == 1: v = vv[0] adjm[v].remove(parent[v]) continue x, d1 = query(vv) if d1 == d: v = x adjm[v].remove(parent[v]) vv, _ = nodes_at_depth(n, v, adjm, 1) x, d1 = query(vv) if d1 == d: v = x vv, _ = nodes_at_depth(n, v, adj, d) w, _ = query(vv) return v, w if __name__ == "__main__": main() ```
instruction
0
51,515
13
103,030
No
output
1
51,515
13
103,031
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Note that the only difference between the easy and hard version is the constraint on the number of queries. You can make hacks only if all versions of the problem are solved. This is an interactive problem. You are given a tree consisting of n nodes numbered with integers from 1 to n. Ayush and Ashish chose two secret distinct nodes in the tree. You need to find out both the nodes. You can make the following query: * Provide a list of nodes and you will receive a node from that list whose sum of distances to both the hidden nodes is minimal (if there are multiple such nodes in the list, you will receive any one of them). You will also get the sum of distances of that node to the hidden nodes. Recall that a tree is a connected graph without cycles. The distance between two nodes is defined as the number of edges in the simple path between them. More formally, let's define two hidden nodes as s and f. In one query you can provide the set of nodes \\{a_1, a_2, …, a_c\} of the tree. As a result, you will get two numbers a_i and dist(a_i, s) + dist(a_i, f). The node a_i is any node from the provided set, for which the number dist(a_i, s) + dist(a_i, f) is minimal. You can ask no more than 14 queries. Input The first line contains a single integer t (1 ≤ t ≤ 10) — the number of test cases. Please note, how the interaction process is organized. The first line of each test case consists of a single integer n (2 ≤ n ≤ 1000) — the number of nodes in the tree. The next n - 1 lines consist of two integers u, v (1 ≤ u, v ≤ n, u ≠ v) — the edges of the tree. Interaction To ask a query print a single line: * In the beginning print "? c " (without quotes) where c (1 ≤ c ≤ n) denotes the number of nodes being queried, followed by c distinct integers in the range [1, n] — the indices of nodes from the list. For each query, you will receive two integers x, d — the node (among the queried nodes) with the minimum sum of distances to the hidden nodes and the sum of distances from that node to the hidden nodes. If the subset of nodes queried is invalid or you exceeded the number of queries then you will get x = d = -1. In this case, you should terminate the program immediately. When you have guessed the hidden nodes, print a single line "! " (without quotes), followed by two integers in the range [1, n] — the hidden nodes. You can output the hidden nodes in any order. After this, you should read a string. If you guess the nodes correctly, you will receive the string "Correct". In this case, you should continue solving the remaining test cases or terminate the program, if all test cases were solved. Otherwise, you will receive the string "Incorrect". In this case, you should terminate the program immediately. Guessing the hidden nodes does not count towards the number of queries asked. The interactor is not adaptive. The hidden nodes do not change with queries. Do not forget to read the string "Correct" / "Incorrect" after guessing the hidden nodes. You need to solve each test case before receiving the input for the next test case. The limit of 14 queries applies to each test case and not to the entire input. After printing a query do not forget to output the end of the line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use: * fflush(stdout) or cout.flush() in C++; * System.out.flush() in Java; * flush(output) in Pascal; * stdout.flush() in Python; * see the documentation for other languages. Hacks To hack the solution, use the following test format: The first line should contain a single integer t (1 ≤ t ≤ 10) — the number of test cases. The description of the test cases follows. The first line of each test case should contain a single integer n (2 ≤ n ≤ 1000) — the number of nodes in the tree. The second line should contain two distinct integers in the range [1, n] — the hidden nodes. The next n - 1 lines should contain two integers u, v (1 ≤ u, v ≤ n, u ≠ v) — the edges of the tree. Example Input 1 3 1 2 1 3 1 1 2 3 3 1 3 1 Correct Output ? 1 1 ? 1 2 ? 1 3 ? 2 2 3 ! 1 3 Note The tree from the first test is shown below, and the hidden nodes are 1 and 3. <image> Submitted Solution: ``` #!/usr/bin/env python from sys import stdout from io import BytesIO, IOBase from bisect import bisect_right,bisect_left mod=998244353 def query(lis): print('?',len(lis),*lis) stdout.flush() x,d=map(int,input().split()) return x,d def dfs(arr,graph,node,dist,pathh_len,parent): if dist>pathh_len: return for adj in graph[node]: if adj!=parent: dfs(arr,graph,adj,dist+1,pathh_len,node) arr.append((node,dist)) def main(): n=int(input()) graph=[[] for i in range(n+1)] for i in range(n-1): u,v=map(int ,input().split()) graph[u].append(v) graph[v].append(u) root,pathh_len=query(list(range(1,n+1))) arr=[] dfs(arr,graph,root,0,pathh_len,-1) arr.sort(key=lambda x:x[1]) # print(graph) # print(arr) a=[] b=[] for i,j in arr: a.append(i) b.append(j) # print(a) # print(b) l=pathh_len//2 r=pathh_len prev=root while l<=r: # print("::",l,r) mid=l+(r-l)//2 ind1=bisect_left(b,mid) ind2=bisect_right(b,r) if len(a[ind1:ind2])==0: break x,p_l=query(a[ind1:ind2]) if p_l>pathh_len: r=mid-1 else: prev=x l=mid+1 arr=[] # print(pathh_len) dfs(arr,graph,prev,0,pathh_len,-1) # print(arr) q=[] assert(pathh_len>0) for i,j in arr: if j==pathh_len: q.append(i) a_,p=query(q) print('!',prev,a_) s=input() assert(s=='Correct') if __name__=='__main__': for _ in range(int(input())): main() ```
instruction
0
51,516
13
103,032
No
output
1
51,516
13
103,033
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Note that the only difference between the easy and hard version is the constraint on the number of queries. You can make hacks only if all versions of the problem are solved. This is an interactive problem. You are given a tree consisting of n nodes numbered with integers from 1 to n. Ayush and Ashish chose two secret distinct nodes in the tree. You need to find out both the nodes. You can make the following query: * Provide a list of nodes and you will receive a node from that list whose sum of distances to both the hidden nodes is minimal (if there are multiple such nodes in the list, you will receive any one of them). You will also get the sum of distances of that node to the hidden nodes. Recall that a tree is a connected graph without cycles. The distance between two nodes is defined as the number of edges in the simple path between them. More formally, let's define two hidden nodes as s and f. In one query you can provide the set of nodes \\{a_1, a_2, …, a_c\} of the tree. As a result, you will get two numbers a_i and dist(a_i, s) + dist(a_i, f). The node a_i is any node from the provided set, for which the number dist(a_i, s) + dist(a_i, f) is minimal. You can ask no more than 14 queries. Input The first line contains a single integer t (1 ≤ t ≤ 10) — the number of test cases. Please note, how the interaction process is organized. The first line of each test case consists of a single integer n (2 ≤ n ≤ 1000) — the number of nodes in the tree. The next n - 1 lines consist of two integers u, v (1 ≤ u, v ≤ n, u ≠ v) — the edges of the tree. Interaction To ask a query print a single line: * In the beginning print "? c " (without quotes) where c (1 ≤ c ≤ n) denotes the number of nodes being queried, followed by c distinct integers in the range [1, n] — the indices of nodes from the list. For each query, you will receive two integers x, d — the node (among the queried nodes) with the minimum sum of distances to the hidden nodes and the sum of distances from that node to the hidden nodes. If the subset of nodes queried is invalid or you exceeded the number of queries then you will get x = d = -1. In this case, you should terminate the program immediately. When you have guessed the hidden nodes, print a single line "! " (without quotes), followed by two integers in the range [1, n] — the hidden nodes. You can output the hidden nodes in any order. After this, you should read a string. If you guess the nodes correctly, you will receive the string "Correct". In this case, you should continue solving the remaining test cases or terminate the program, if all test cases were solved. Otherwise, you will receive the string "Incorrect". In this case, you should terminate the program immediately. Guessing the hidden nodes does not count towards the number of queries asked. The interactor is not adaptive. The hidden nodes do not change with queries. Do not forget to read the string "Correct" / "Incorrect" after guessing the hidden nodes. You need to solve each test case before receiving the input for the next test case. The limit of 14 queries applies to each test case and not to the entire input. After printing a query do not forget to output the end of the line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use: * fflush(stdout) or cout.flush() in C++; * System.out.flush() in Java; * flush(output) in Pascal; * stdout.flush() in Python; * see the documentation for other languages. Hacks To hack the solution, use the following test format: The first line should contain a single integer t (1 ≤ t ≤ 10) — the number of test cases. The description of the test cases follows. The first line of each test case should contain a single integer n (2 ≤ n ≤ 1000) — the number of nodes in the tree. The second line should contain two distinct integers in the range [1, n] — the hidden nodes. The next n - 1 lines should contain two integers u, v (1 ≤ u, v ≤ n, u ≠ v) — the edges of the tree. Example Input 1 3 1 2 1 3 1 1 2 3 3 1 3 1 Correct Output ? 1 1 ? 1 2 ? 1 3 ? 2 2 3 ! 1 3 Note The tree from the first test is shown below, and the hidden nodes are 1 and 3. <image> Submitted Solution: ``` def query(subsets, indeces): print(indeces) print("?", sum([len(subsets[i]) for i in indeces]), end = " ") for i in indeces: for num in subsets[i]: print(num, end = " ") print() return int(input()) for _ in range(int(input())): n, k = map(int, input().split()) subsets = [] for _ in range(k): subsets.append(list(map(int, input().split()))[1:]) lo = 0 hi = k-1 while lo < hi: mid = (lo + hi) // 2 res = query(subsets, [i for i in range(lo, mid+1)]) if res == n: hi = mid else: lo = mid + 1 number = query(subsets, [i for i in range(k) if i != lo]) print("!", end = " ") for i in range(k): if i == lo: print(number, end = " ") else: print(n, end = " ") print() if input() == "Incorrect": print("NOoooooooo") exit() ```
instruction
0
51,517
13
103,034
No
output
1
51,517
13
103,035
Evaluate the correctness of the submitted Python 2 solution to the coding contest problem. Provide a "Yes" or "No" response. Note that the only difference between the easy and hard version is the constraint on the number of queries. You can make hacks only if all versions of the problem are solved. This is an interactive problem. You are given a tree consisting of n nodes numbered with integers from 1 to n. Ayush and Ashish chose two secret distinct nodes in the tree. You need to find out both the nodes. You can make the following query: * Provide a list of nodes and you will receive a node from that list whose sum of distances to both the hidden nodes is minimal (if there are multiple such nodes in the list, you will receive any one of them). You will also get the sum of distances of that node to the hidden nodes. Recall that a tree is a connected graph without cycles. The distance between two nodes is defined as the number of edges in the simple path between them. More formally, let's define two hidden nodes as s and f. In one query you can provide the set of nodes \\{a_1, a_2, …, a_c\} of the tree. As a result, you will get two numbers a_i and dist(a_i, s) + dist(a_i, f). The node a_i is any node from the provided set, for which the number dist(a_i, s) + dist(a_i, f) is minimal. You can ask no more than 14 queries. Input The first line contains a single integer t (1 ≤ t ≤ 10) — the number of test cases. Please note, how the interaction process is organized. The first line of each test case consists of a single integer n (2 ≤ n ≤ 1000) — the number of nodes in the tree. The next n - 1 lines consist of two integers u, v (1 ≤ u, v ≤ n, u ≠ v) — the edges of the tree. Interaction To ask a query print a single line: * In the beginning print "? c " (without quotes) where c (1 ≤ c ≤ n) denotes the number of nodes being queried, followed by c distinct integers in the range [1, n] — the indices of nodes from the list. For each query, you will receive two integers x, d — the node (among the queried nodes) with the minimum sum of distances to the hidden nodes and the sum of distances from that node to the hidden nodes. If the subset of nodes queried is invalid or you exceeded the number of queries then you will get x = d = -1. In this case, you should terminate the program immediately. When you have guessed the hidden nodes, print a single line "! " (without quotes), followed by two integers in the range [1, n] — the hidden nodes. You can output the hidden nodes in any order. After this, you should read a string. If you guess the nodes correctly, you will receive the string "Correct". In this case, you should continue solving the remaining test cases or terminate the program, if all test cases were solved. Otherwise, you will receive the string "Incorrect". In this case, you should terminate the program immediately. Guessing the hidden nodes does not count towards the number of queries asked. The interactor is not adaptive. The hidden nodes do not change with queries. Do not forget to read the string "Correct" / "Incorrect" after guessing the hidden nodes. You need to solve each test case before receiving the input for the next test case. The limit of 14 queries applies to each test case and not to the entire input. After printing a query do not forget to output the end of the line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use: * fflush(stdout) or cout.flush() in C++; * System.out.flush() in Java; * flush(output) in Pascal; * stdout.flush() in Python; * see the documentation for other languages. Hacks To hack the solution, use the following test format: The first line should contain a single integer t (1 ≤ t ≤ 10) — the number of test cases. The description of the test cases follows. The first line of each test case should contain a single integer n (2 ≤ n ≤ 1000) — the number of nodes in the tree. The second line should contain two distinct integers in the range [1, n] — the hidden nodes. The next n - 1 lines should contain two integers u, v (1 ≤ u, v ≤ n, u ≠ v) — the edges of the tree. Example Input 1 3 1 2 1 3 1 1 2 3 3 1 3 1 Correct Output ? 1 1 ? 1 2 ? 1 3 ? 2 2 3 ! 1 3 Note The tree from the first test is shown below, and the hidden nodes are 1 and 3. <image> Submitted Solution: ``` from sys import stdin, stdout from collections import Counter, defaultdict from itertools import permutations, combinations raw_input = stdin.readline pr = stdout.write mod=10**9+7 def ni(): return int(raw_input()) def li(): return map(int,raw_input().split()) def pn(n): stdout.write(str(n)+'\n') def pa(arr): pr(' '.join(map(str,arr))+'\n') # fast read function for total integer input def inp(): # this function returns whole input of # space/line seperated integers # Use Ctrl+D to flush stdin. return map(int,stdin.read().split()) range = xrange # not for python 3.0+ for t in range(ni()): n,k=li() ans=[1]*k d=Counter() ip=[li() for i in range(k)] for i1 in range(k): x=ip[i1] n1=x.pop(0) s1=set(range(1,n+1))-set(x) mx=0 for i in d: if d[i] and set(i).intersection(s1)==set(i): s1-=set(i) mx=max(mx,d[i]) if not s1: ans[i1]=mx continue stdout.write('? '+str(len(s1))+' ') for i in s1: stdout.write(str(i)+' ') stdout.write('\n') stdout.flush() inp=ni() d[tuple(sorted(s1))]=inp mx=max(mx,inp) ans[i1]=mx stdout.write('! ') for i in ans: stdout.write(str(i)+' ') stdout.write('\n') stdout.flush() x=raw_input().strip() ```
instruction
0
51,518
13
103,036
No
output
1
51,518
13
103,037
Provide tags and a correct Python 3 solution for this coding contest problem. You are given n - 1 integers a_2, ..., a_n and a tree with n vertices rooted at vertex 1. The leaves are all at the same distance d from the root. Recall that a tree is a connected undirected graph without cycles. The distance between two vertices is the number of edges on the simple path between them. All non-root vertices with degree 1 are leaves. If vertices s and f are connected by an edge and the distance of f from the root is greater than the distance of s from the root, then f is called a child of s. Initially, there are a red coin and a blue coin on the vertex 1. Let r be the vertex where the red coin is and let b be the vertex where the blue coin is. You should make d moves. A move consists of three steps: * Move the red coin to any child of r. * Move the blue coin to any vertex b' such that dist(1, b') = dist(1, b) + 1. Here dist(x, y) indicates the length of the simple path between x and y. Note that b and b' are not necessarily connected by an edge. * You can optionally swap the two coins (or skip this step). Note that r and b can be equal at any time, and there is no number written on the root. After each move, you gain |a_r - a_b| points. What's the maximum number of points you can gain after d moves? Input The first line contains a single integer t (1 ≤ t ≤ 10^4) — the number of test cases. The first line of each test case contains a single integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of vertices in the tree. The second line of each test case contains n-1 integers v_2, v_3, ..., v_n (1 ≤ v_i ≤ n, v_i ≠ i) — the i-th of them indicates that there is an edge between vertices i and v_i. It is guaranteed, that these edges form a tree. The third line of each test case contains n-1 integers a_2, ..., a_n (1 ≤ a_i ≤ 10^9) — the numbers written on the vertices. It is guaranteed that the sum of n for all test cases does not exceed 2 ⋅ 10^5. Output For each test case, print a single integer: the maximum number of points you can gain after d moves. Example Input 4 14 1 1 1 2 3 4 4 5 5 6 7 8 8 2 3 7 7 6 9 5 9 7 3 6 6 5 6 1 2 2 3 4 32 78 69 5 41 15 1 15 1 10 4 9 11 2 4 1 8 6 10 11 62 13 12 43 39 65 42 86 25 38 19 19 43 62 15 11 2 7 6 9 8 10 1 1 1 5 3 15 2 50 19 30 35 9 45 13 24 8 44 16 26 10 40 Output 14 45 163 123 Note In the first test case, an optimal solution is to: * move 1: r = 4, b = 2; no swap; * move 2: r = 7, b = 6; swap (after it r = 6, b = 7); * move 3: r = 11, b = 9; no swap. The total number of points is |7 - 2| + |6 - 9| + |3 - 9| = 14. <image> In the second test case, an optimal solution is to: * move 1: r = 2, b = 2; no swap; * move 2: r = 3, b = 4; no swap; * move 3: r = 5, b = 6; no swap. The total number of points is |32 - 32| + |78 - 69| + |5 - 41| = 45.
instruction
0
51,557
13
103,114
Tags: dfs and similar, dp, greedy, trees Correct Solution: ``` from collections import deque T = int(input()) def solve(E, W): nodes = {idx: (w, []) for idx, w in weights.items()} for u, v in E: nodes[u][1].append(v) nodes[v][1].append(u) layers = [] visited = set([1]) parents = {idx: None for idx in weights.keys()} Q = deque([1]) while Q: layers.append(list(Q)) l = len(Q) for _ in range(l): cur_idx = Q.popleft() for v in nodes[cur_idx][1]: if v not in visited: Q.append(v) visited.add(v) parents[v] = cur_idx dp_b = {idx: 0 for idx in weights.keys()} dp_r = {idx: 0 for idx in weights.keys()} for l in range(1, len(layers)): max_w = max([nodes[idx][0] for idx in layers[l]]) min_w = min([nodes[idx][0] for idx in layers[l]]) max_dpp_add, max_dpp_sub = -1e10, -1e10 for v in layers[l]: pv = parents[v] max_dpp_add = max(max_dpp_add, max(dp_r[pv], dp_b[pv]) + nodes[v][0]) max_dpp_sub = max(max_dpp_sub, max(dp_r[pv], dp_b[pv]) - nodes[v][0]) for u in layers[l]: p = parents[u] dp_r[u] = max( dp_r[p] + max(nodes[u][0] - min_w, max_w - nodes[u][0]), dp_b[p] + max(nodes[u][0] - min_w, max_w - nodes[u][0]) ) # for v in layers[l]: # pv = parents[v] # dp_b[u] = max(dp_b[u], max(dp_r[pv], dp_b[pv]) + abs(nodes[u][0] - nodes[v][0])) dp_b[u] = max(max_dpp_add - nodes[u][0], max_dpp_sub + nodes[u][0]) # print('layers: {}'.format(layers)) # print('dp: {}'.format(dp_r)) return max([dp_r[idx] for idx in layers[-1]]) for _ in range(T): n = int(input()) V = list(map(int, input().split(' '))) W = list(map(int, input().split(' '))) edges = [] weights = {1: 0} for i in range(n-1): edges.append((i+2, V[i])) for i in range(n-1): weights[i+2] = W[i] print(solve(edges, weights)) ```
output
1
51,557
13
103,115
Provide tags and a correct Python 3 solution for this coding contest problem. You are given n - 1 integers a_2, ..., a_n and a tree with n vertices rooted at vertex 1. The leaves are all at the same distance d from the root. Recall that a tree is a connected undirected graph without cycles. The distance between two vertices is the number of edges on the simple path between them. All non-root vertices with degree 1 are leaves. If vertices s and f are connected by an edge and the distance of f from the root is greater than the distance of s from the root, then f is called a child of s. Initially, there are a red coin and a blue coin on the vertex 1. Let r be the vertex where the red coin is and let b be the vertex where the blue coin is. You should make d moves. A move consists of three steps: * Move the red coin to any child of r. * Move the blue coin to any vertex b' such that dist(1, b') = dist(1, b) + 1. Here dist(x, y) indicates the length of the simple path between x and y. Note that b and b' are not necessarily connected by an edge. * You can optionally swap the two coins (or skip this step). Note that r and b can be equal at any time, and there is no number written on the root. After each move, you gain |a_r - a_b| points. What's the maximum number of points you can gain after d moves? Input The first line contains a single integer t (1 ≤ t ≤ 10^4) — the number of test cases. The first line of each test case contains a single integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of vertices in the tree. The second line of each test case contains n-1 integers v_2, v_3, ..., v_n (1 ≤ v_i ≤ n, v_i ≠ i) — the i-th of them indicates that there is an edge between vertices i and v_i. It is guaranteed, that these edges form a tree. The third line of each test case contains n-1 integers a_2, ..., a_n (1 ≤ a_i ≤ 10^9) — the numbers written on the vertices. It is guaranteed that the sum of n for all test cases does not exceed 2 ⋅ 10^5. Output For each test case, print a single integer: the maximum number of points you can gain after d moves. Example Input 4 14 1 1 1 2 3 4 4 5 5 6 7 8 8 2 3 7 7 6 9 5 9 7 3 6 6 5 6 1 2 2 3 4 32 78 69 5 41 15 1 15 1 10 4 9 11 2 4 1 8 6 10 11 62 13 12 43 39 65 42 86 25 38 19 19 43 62 15 11 2 7 6 9 8 10 1 1 1 5 3 15 2 50 19 30 35 9 45 13 24 8 44 16 26 10 40 Output 14 45 163 123 Note In the first test case, an optimal solution is to: * move 1: r = 4, b = 2; no swap; * move 2: r = 7, b = 6; swap (after it r = 6, b = 7); * move 3: r = 11, b = 9; no swap. The total number of points is |7 - 2| + |6 - 9| + |3 - 9| = 14. <image> In the second test case, an optimal solution is to: * move 1: r = 2, b = 2; no swap; * move 2: r = 3, b = 4; no swap; * move 3: r = 5, b = 6; no swap. The total number of points is |32 - 32| + |78 - 69| + |5 - 41| = 45.
instruction
0
51,558
13
103,116
Tags: dfs and similar, dp, greedy, trees Correct Solution: ``` #import sys #input = lambda: sys.stdin.readline().rstrip() from collections import deque T = int(input()) for _ in range(T): N = int(input()) X = [[] for i in range(N)] pp = [int(a)-1 for a in input().split()] for i, p in enumerate(pp, 1): X[i].append(p) X[p].append(i) P = [-1] * N Q = deque([0]) R = [] while Q: i = deque.popleft(Q) R.append(i) for a in X[i]: if a != P[i]: P[a] = i X[a].remove(i) deque.append(Q, a) Y = [[0]] D = [0] * N for i in R[1:]: D[i] = D[P[i]] + 1 while len(Y) <= D[i]: Y.append([]) Y[D[i]].append(i) A = [0] + [int(a) for a in input().split()] d = max(D) + 1 MI = [10 ** 9] * d MA = [0] * d for i, a in enumerate(A): MI[D[i]] = min(MI[D[i]], a) MA[D[i]] = max(MA[D[i]], a) S = [0] * N for i in Y[-1]: S[i] = max(abs(A[i] - MA[-1]), abs(A[i] - MI[-1])) for de in range(d - 1)[::-1]: abc1 = 0 abc2 = - 10 ** 9 for i in Y[de]: ma = 0 for j in X[i]: ma = max(ma, S[j]) abc1 = max(abc1, ma + A[i]) abc2 = max(abc2, ma - A[i]) S[i] = max(abs(A[i] - MI[de]), abs(MA[de] - A[i])) + ma for i in Y[de]: S[i] = max(S[i], abc1 - A[i], abc2 + A[i]) print(S[0]) ```
output
1
51,558
13
103,117
Provide tags and a correct Python 3 solution for this coding contest problem. You are given n - 1 integers a_2, ..., a_n and a tree with n vertices rooted at vertex 1. The leaves are all at the same distance d from the root. Recall that a tree is a connected undirected graph without cycles. The distance between two vertices is the number of edges on the simple path between them. All non-root vertices with degree 1 are leaves. If vertices s and f are connected by an edge and the distance of f from the root is greater than the distance of s from the root, then f is called a child of s. Initially, there are a red coin and a blue coin on the vertex 1. Let r be the vertex where the red coin is and let b be the vertex where the blue coin is. You should make d moves. A move consists of three steps: * Move the red coin to any child of r. * Move the blue coin to any vertex b' such that dist(1, b') = dist(1, b) + 1. Here dist(x, y) indicates the length of the simple path between x and y. Note that b and b' are not necessarily connected by an edge. * You can optionally swap the two coins (or skip this step). Note that r and b can be equal at any time, and there is no number written on the root. After each move, you gain |a_r - a_b| points. What's the maximum number of points you can gain after d moves? Input The first line contains a single integer t (1 ≤ t ≤ 10^4) — the number of test cases. The first line of each test case contains a single integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of vertices in the tree. The second line of each test case contains n-1 integers v_2, v_3, ..., v_n (1 ≤ v_i ≤ n, v_i ≠ i) — the i-th of them indicates that there is an edge between vertices i and v_i. It is guaranteed, that these edges form a tree. The third line of each test case contains n-1 integers a_2, ..., a_n (1 ≤ a_i ≤ 10^9) — the numbers written on the vertices. It is guaranteed that the sum of n for all test cases does not exceed 2 ⋅ 10^5. Output For each test case, print a single integer: the maximum number of points you can gain after d moves. Example Input 4 14 1 1 1 2 3 4 4 5 5 6 7 8 8 2 3 7 7 6 9 5 9 7 3 6 6 5 6 1 2 2 3 4 32 78 69 5 41 15 1 15 1 10 4 9 11 2 4 1 8 6 10 11 62 13 12 43 39 65 42 86 25 38 19 19 43 62 15 11 2 7 6 9 8 10 1 1 1 5 3 15 2 50 19 30 35 9 45 13 24 8 44 16 26 10 40 Output 14 45 163 123 Note In the first test case, an optimal solution is to: * move 1: r = 4, b = 2; no swap; * move 2: r = 7, b = 6; swap (after it r = 6, b = 7); * move 3: r = 11, b = 9; no swap. The total number of points is |7 - 2| + |6 - 9| + |3 - 9| = 14. <image> In the second test case, an optimal solution is to: * move 1: r = 2, b = 2; no swap; * move 2: r = 3, b = 4; no swap; * move 3: r = 5, b = 6; no swap. The total number of points is |32 - 32| + |78 - 69| + |5 - 41| = 45.
instruction
0
51,559
13
103,118
Tags: dfs and similar, dp, greedy, trees Correct Solution: ``` import sys import collections def read_ints(): return [int(i) for i in sys.stdin.readline().strip().split()] def read_int(): return int(sys.stdin.readline().strip()) class Node: def __init__(self, id, number, parent): self.id = id self.parent = parent self.children = [] self.number = number if self.parent is None: self.depth = 0 else: self.depth = self.parent.depth + 1 self.score = 0 def add_child(self, child): self.children.append(child) def __repr__(self): return ("Node %d (depth %d) with number %d, parent %s" % (self.id, self.depth, self.number, str(self.parent and self.parent.id))) def solve(n, edges, nums): neighbours = [] for i in range(n + 1): neighbours.append([]) for i in range(n - 1): neighbours[i + 2].append(edges[i]) neighbours[edges[i]].append(i + 2) #print(neighbours) root = Node(1, 0, None) nodes = {1 : root} tier = [1] depths = collections.defaultdict(list) depths[0].append(root) max_depth = 0 while tier: new_tier = [] for parent_id in tier: for node_id in neighbours[parent_id]: if node_id not in nodes: child = Node(node_id, nums[node_id - 2], nodes[parent_id]) depths[child.depth].append(child) max_depth = child.depth nodes[node_id] = child nodes[parent_id].add_child(child) new_tier.append(node_id) tier = new_tier[:] #for id, node in nodes.items(): #print(id, node) #for d, nodes in depths.items(): #print(d, [n.id for n in nodes]) depth = max_depth while depth > 0: tier = depths[depth] scores = [n.number for n in tier] for node in tier: if node.children: node.best_child_score = max(n.score for n in node.children) else: node.best_child_score = 0 min_score = min(scores) max_score = max(scores) min_score_with_children = min(n.number - n.best_child_score for n in tier) max_score_with_children = max(n.number + n.best_child_score for n in tier) for n in tier: n.score = max(n.number - min_score_with_children, max_score_with_children - n.number, n.best_child_score + n.number - min_score, n.best_child_score + max_score - n.number) #print("Depth %d" % depth) #for n in tier: #print(n.id, n.score) depth -= 1 return max(n.score for n in depths[1]) t = read_int() for i in range(t): n = read_int() edges = read_ints() nums = read_ints() print(solve(n, edges, nums)) ```
output
1
51,559
13
103,119
Provide tags and a correct Python 3 solution for this coding contest problem. You are given n - 1 integers a_2, ..., a_n and a tree with n vertices rooted at vertex 1. The leaves are all at the same distance d from the root. Recall that a tree is a connected undirected graph without cycles. The distance between two vertices is the number of edges on the simple path between them. All non-root vertices with degree 1 are leaves. If vertices s and f are connected by an edge and the distance of f from the root is greater than the distance of s from the root, then f is called a child of s. Initially, there are a red coin and a blue coin on the vertex 1. Let r be the vertex where the red coin is and let b be the vertex where the blue coin is. You should make d moves. A move consists of three steps: * Move the red coin to any child of r. * Move the blue coin to any vertex b' such that dist(1, b') = dist(1, b) + 1. Here dist(x, y) indicates the length of the simple path between x and y. Note that b and b' are not necessarily connected by an edge. * You can optionally swap the two coins (or skip this step). Note that r and b can be equal at any time, and there is no number written on the root. After each move, you gain |a_r - a_b| points. What's the maximum number of points you can gain after d moves? Input The first line contains a single integer t (1 ≤ t ≤ 10^4) — the number of test cases. The first line of each test case contains a single integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of vertices in the tree. The second line of each test case contains n-1 integers v_2, v_3, ..., v_n (1 ≤ v_i ≤ n, v_i ≠ i) — the i-th of them indicates that there is an edge between vertices i and v_i. It is guaranteed, that these edges form a tree. The third line of each test case contains n-1 integers a_2, ..., a_n (1 ≤ a_i ≤ 10^9) — the numbers written on the vertices. It is guaranteed that the sum of n for all test cases does not exceed 2 ⋅ 10^5. Output For each test case, print a single integer: the maximum number of points you can gain after d moves. Example Input 4 14 1 1 1 2 3 4 4 5 5 6 7 8 8 2 3 7 7 6 9 5 9 7 3 6 6 5 6 1 2 2 3 4 32 78 69 5 41 15 1 15 1 10 4 9 11 2 4 1 8 6 10 11 62 13 12 43 39 65 42 86 25 38 19 19 43 62 15 11 2 7 6 9 8 10 1 1 1 5 3 15 2 50 19 30 35 9 45 13 24 8 44 16 26 10 40 Output 14 45 163 123 Note In the first test case, an optimal solution is to: * move 1: r = 4, b = 2; no swap; * move 2: r = 7, b = 6; swap (after it r = 6, b = 7); * move 3: r = 11, b = 9; no swap. The total number of points is |7 - 2| + |6 - 9| + |3 - 9| = 14. <image> In the second test case, an optimal solution is to: * move 1: r = 2, b = 2; no swap; * move 2: r = 3, b = 4; no swap; * move 3: r = 5, b = 6; no swap. The total number of points is |32 - 32| + |78 - 69| + |5 - 41| = 45.
instruction
0
51,560
13
103,120
Tags: dfs and similar, dp, greedy, trees Correct Solution: ``` from sys import stdin import sys 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 tt = int(stdin.readline()) for loop in range(tt): n = int(stdin.readline()) lis = [ [] for i in range(n) ] vl = list(map(int,stdin.readline().split())) a = [0] + list(map(int,stdin.readline().split())) for i in range(n-1): vl[i] -= 1 lis[i+1].append(vl[i]) lis[vl[i]].append(i+1) dis,tmp = NC_Dij(lis,0) d = max(dis) dtov = [ [] for i in range(d+1) ] for i in range(n): dtov[dis[i]].append(i) dp = [0] * n for nd in range(d,-1,-1): av = [] for v in dtov[nd]: av.append((a[v] , v)) av.sort() childmax = [0] * len(av) for i in range(len(av)): na,nv = av[i] for c in lis[nv]: childmax[i] = max(childmax[i] , dp[c]) leftmax = [ float("-inf") ] * len(av) tmpmax = float("-inf") for i in range(len(av)): na,nv = av[i] tmpmax = max(tmpmax , childmax[i] - na) leftmax[i] = tmpmax rightmax = [ float("-inf") ] * len(av) tmpmax = float("-inf") for i in range(len(av)-1,-1,-1): na,nv = av[i] tmpmax = max(tmpmax , childmax[i] + na) rightmax[i] = tmpmax #print (av) #print (leftmax,rightmax) #dp for i in range(len(av)): na,nv = av[i] dp[nv] = max(dp[nv] , leftmax[i] + na , rightmax[i] - na) dp[nv] = max(dp[nv] , childmax[i] + max( abs(na-av[0][0]),abs(na-av[-1][0]) ) ) print (dp[0]) ```
output
1
51,560
13
103,121
Provide tags and a correct Python 3 solution for this coding contest problem. You are given n - 1 integers a_2, ..., a_n and a tree with n vertices rooted at vertex 1. The leaves are all at the same distance d from the root. Recall that a tree is a connected undirected graph without cycles. The distance between two vertices is the number of edges on the simple path between them. All non-root vertices with degree 1 are leaves. If vertices s and f are connected by an edge and the distance of f from the root is greater than the distance of s from the root, then f is called a child of s. Initially, there are a red coin and a blue coin on the vertex 1. Let r be the vertex where the red coin is and let b be the vertex where the blue coin is. You should make d moves. A move consists of three steps: * Move the red coin to any child of r. * Move the blue coin to any vertex b' such that dist(1, b') = dist(1, b) + 1. Here dist(x, y) indicates the length of the simple path between x and y. Note that b and b' are not necessarily connected by an edge. * You can optionally swap the two coins (or skip this step). Note that r and b can be equal at any time, and there is no number written on the root. After each move, you gain |a_r - a_b| points. What's the maximum number of points you can gain after d moves? Input The first line contains a single integer t (1 ≤ t ≤ 10^4) — the number of test cases. The first line of each test case contains a single integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of vertices in the tree. The second line of each test case contains n-1 integers v_2, v_3, ..., v_n (1 ≤ v_i ≤ n, v_i ≠ i) — the i-th of them indicates that there is an edge between vertices i and v_i. It is guaranteed, that these edges form a tree. The third line of each test case contains n-1 integers a_2, ..., a_n (1 ≤ a_i ≤ 10^9) — the numbers written on the vertices. It is guaranteed that the sum of n for all test cases does not exceed 2 ⋅ 10^5. Output For each test case, print a single integer: the maximum number of points you can gain after d moves. Example Input 4 14 1 1 1 2 3 4 4 5 5 6 7 8 8 2 3 7 7 6 9 5 9 7 3 6 6 5 6 1 2 2 3 4 32 78 69 5 41 15 1 15 1 10 4 9 11 2 4 1 8 6 10 11 62 13 12 43 39 65 42 86 25 38 19 19 43 62 15 11 2 7 6 9 8 10 1 1 1 5 3 15 2 50 19 30 35 9 45 13 24 8 44 16 26 10 40 Output 14 45 163 123 Note In the first test case, an optimal solution is to: * move 1: r = 4, b = 2; no swap; * move 2: r = 7, b = 6; swap (after it r = 6, b = 7); * move 3: r = 11, b = 9; no swap. The total number of points is |7 - 2| + |6 - 9| + |3 - 9| = 14. <image> In the second test case, an optimal solution is to: * move 1: r = 2, b = 2; no swap; * move 2: r = 3, b = 4; no swap; * move 3: r = 5, b = 6; no swap. The total number of points is |32 - 32| + |78 - 69| + |5 - 41| = 45.
instruction
0
51,561
13
103,122
Tags: dfs and similar, dp, greedy, trees Correct Solution: ``` from collections import defaultdict def main(): cases = int(input()) ans_list = [] for _ in range(cases): n = int(input()) dp = [0 for i in range(n+1)] graph = defaultdict(set) edges = list(map(int, input().split(' '))) values = list(map(int, input().split())) for i, val in enumerate(edges): graph[i+2].add(val) graph[val].add(i+2) levels = [[(1,0)]] stack = [(1,0)] while stack: cur_node, cur_level = stack.pop() for adj in graph[cur_node]: stack.append((adj, cur_level+1)) graph[adj].remove(cur_node) if cur_level + 1 >= len(levels): levels.append([]) levels[cur_level+1].append((adj, values[adj-2])) for l in range(len(levels)-1, -1, -1): levels[l] = sorted(levels[l], key=lambda x:x[1]) neg = float('inf') child_max = [] for (node, val) in levels[l]: cur_max = 0 for child in graph[node]: cur_max = max(dp[child], cur_max) child_max.append(cur_max) if l == 0: ans_list.append(child_max[0]) break cur_best = float('-inf') for i, (node, val) in enumerate(levels[l]): dp[node] = max(dp[node], cur_best + val, ) cur_best = max(cur_best, child_max[i]-val) cur_best = float('-inf') for i in range(len(levels[l])-1, -1, -1): node, val = levels[l][i] dp[node] = max(dp[node], cur_best - val) cur_best = max(cur_best, child_max[i]+val) for i, (node, val) in enumerate(levels[l]): dp[node] = max( dp[node], child_max[i] + max(abs(val-levels[l][0][1]), abs(val-levels[l][-1][1])) ) print('\n'.join(map(str, ans_list))) # region fastio 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") # endregion if __name__ == "__main__": main() ```
output
1
51,561
13
103,123
Provide tags and a correct Python 3 solution for this coding contest problem. You are given n - 1 integers a_2, ..., a_n and a tree with n vertices rooted at vertex 1. The leaves are all at the same distance d from the root. Recall that a tree is a connected undirected graph without cycles. The distance between two vertices is the number of edges on the simple path between them. All non-root vertices with degree 1 are leaves. If vertices s and f are connected by an edge and the distance of f from the root is greater than the distance of s from the root, then f is called a child of s. Initially, there are a red coin and a blue coin on the vertex 1. Let r be the vertex where the red coin is and let b be the vertex where the blue coin is. You should make d moves. A move consists of three steps: * Move the red coin to any child of r. * Move the blue coin to any vertex b' such that dist(1, b') = dist(1, b) + 1. Here dist(x, y) indicates the length of the simple path between x and y. Note that b and b' are not necessarily connected by an edge. * You can optionally swap the two coins (or skip this step). Note that r and b can be equal at any time, and there is no number written on the root. After each move, you gain |a_r - a_b| points. What's the maximum number of points you can gain after d moves? Input The first line contains a single integer t (1 ≤ t ≤ 10^4) — the number of test cases. The first line of each test case contains a single integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of vertices in the tree. The second line of each test case contains n-1 integers v_2, v_3, ..., v_n (1 ≤ v_i ≤ n, v_i ≠ i) — the i-th of them indicates that there is an edge between vertices i and v_i. It is guaranteed, that these edges form a tree. The third line of each test case contains n-1 integers a_2, ..., a_n (1 ≤ a_i ≤ 10^9) — the numbers written on the vertices. It is guaranteed that the sum of n for all test cases does not exceed 2 ⋅ 10^5. Output For each test case, print a single integer: the maximum number of points you can gain after d moves. Example Input 4 14 1 1 1 2 3 4 4 5 5 6 7 8 8 2 3 7 7 6 9 5 9 7 3 6 6 5 6 1 2 2 3 4 32 78 69 5 41 15 1 15 1 10 4 9 11 2 4 1 8 6 10 11 62 13 12 43 39 65 42 86 25 38 19 19 43 62 15 11 2 7 6 9 8 10 1 1 1 5 3 15 2 50 19 30 35 9 45 13 24 8 44 16 26 10 40 Output 14 45 163 123 Note In the first test case, an optimal solution is to: * move 1: r = 4, b = 2; no swap; * move 2: r = 7, b = 6; swap (after it r = 6, b = 7); * move 3: r = 11, b = 9; no swap. The total number of points is |7 - 2| + |6 - 9| + |3 - 9| = 14. <image> In the second test case, an optimal solution is to: * move 1: r = 2, b = 2; no swap; * move 2: r = 3, b = 4; no swap; * move 3: r = 5, b = 6; no swap. The total number of points is |32 - 32| + |78 - 69| + |5 - 41| = 45.
instruction
0
51,562
13
103,124
Tags: dfs and similar, dp, greedy, trees Correct Solution: ``` from collections import deque for _ in range(int(input())): N = int(input());X = [[] for i in range(N)];pp = [int(a)-1 for a in input().split()] for i, p in enumerate(pp, 1):X[i].append(p);X[p].append(i) P = [-1] * N;Q = deque([0]);R = [];Y = [[0]];D = [0] * N while Q: i = deque.popleft(Q);R.append(i) for a in X[i]: if a != P[i]:P[a] = i;X[a].remove(i);deque.append(Q, a) for i in R[1:]: D[i] = D[P[i]] + 1 while len(Y) <= D[i]: Y.append([]) Y[D[i]].append(i) A = [0] + [int(a) for a in input().split()];d = max(D) + 1;MI = [10 ** 9] * d;MA = [0] * d;S = [0] * N for i, a in enumerate(A):MI[D[i]] = min(MI[D[i]], a);MA[D[i]] = max(MA[D[i]], a) for i in Y[-1]:S[i] = max(abs(A[i] - MA[-1]), abs(A[i] - MI[-1])) for de in range(d - 1)[::-1]: abc1 = 0;abc2 = - 10 ** 9 for i in Y[de]: ma = 0 for j in X[i]: ma = max(ma, S[j]) abc1 = max(abc1, ma + A[i]);abc2 = max(abc2, ma - A[i]);S[i] = max(abs(A[i] - MI[de]), abs(MA[de] - A[i])) + ma for i in Y[de]:S[i] = max(S[i], abc1 - A[i], abc2 + A[i]) print(S[0]) ```
output
1
51,562
13
103,125
Provide tags and a correct Python 3 solution for this coding contest problem. You are given n - 1 integers a_2, ..., a_n and a tree with n vertices rooted at vertex 1. The leaves are all at the same distance d from the root. Recall that a tree is a connected undirected graph without cycles. The distance between two vertices is the number of edges on the simple path between them. All non-root vertices with degree 1 are leaves. If vertices s and f are connected by an edge and the distance of f from the root is greater than the distance of s from the root, then f is called a child of s. Initially, there are a red coin and a blue coin on the vertex 1. Let r be the vertex where the red coin is and let b be the vertex where the blue coin is. You should make d moves. A move consists of three steps: * Move the red coin to any child of r. * Move the blue coin to any vertex b' such that dist(1, b') = dist(1, b) + 1. Here dist(x, y) indicates the length of the simple path between x and y. Note that b and b' are not necessarily connected by an edge. * You can optionally swap the two coins (or skip this step). Note that r and b can be equal at any time, and there is no number written on the root. After each move, you gain |a_r - a_b| points. What's the maximum number of points you can gain after d moves? Input The first line contains a single integer t (1 ≤ t ≤ 10^4) — the number of test cases. The first line of each test case contains a single integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of vertices in the tree. The second line of each test case contains n-1 integers v_2, v_3, ..., v_n (1 ≤ v_i ≤ n, v_i ≠ i) — the i-th of them indicates that there is an edge between vertices i and v_i. It is guaranteed, that these edges form a tree. The third line of each test case contains n-1 integers a_2, ..., a_n (1 ≤ a_i ≤ 10^9) — the numbers written on the vertices. It is guaranteed that the sum of n for all test cases does not exceed 2 ⋅ 10^5. Output For each test case, print a single integer: the maximum number of points you can gain after d moves. Example Input 4 14 1 1 1 2 3 4 4 5 5 6 7 8 8 2 3 7 7 6 9 5 9 7 3 6 6 5 6 1 2 2 3 4 32 78 69 5 41 15 1 15 1 10 4 9 11 2 4 1 8 6 10 11 62 13 12 43 39 65 42 86 25 38 19 19 43 62 15 11 2 7 6 9 8 10 1 1 1 5 3 15 2 50 19 30 35 9 45 13 24 8 44 16 26 10 40 Output 14 45 163 123 Note In the first test case, an optimal solution is to: * move 1: r = 4, b = 2; no swap; * move 2: r = 7, b = 6; swap (after it r = 6, b = 7); * move 3: r = 11, b = 9; no swap. The total number of points is |7 - 2| + |6 - 9| + |3 - 9| = 14. <image> In the second test case, an optimal solution is to: * move 1: r = 2, b = 2; no swap; * move 2: r = 3, b = 4; no swap; * move 3: r = 5, b = 6; no swap. The total number of points is |32 - 32| + |78 - 69| + |5 - 41| = 45.
instruction
0
51,563
13
103,126
Tags: dfs and similar, dp, greedy, trees Correct Solution: ``` from collections import deque for _ in range(int(input())): N = int(input()) X = [[] for i in range(N)] pp = [int(a)-1 for a in input().split()] for i, p in enumerate(pp, 1): X[i].append(p) X[p].append(i) P = [-1] * N Q = deque([0]) R = [] while Q: i = deque.popleft(Q) R.append(i) for a in X[i]: if a != P[i]: P[a] = i X[a].remove(i) deque.append(Q, a) Y = [[0]] D = [0] * N for i in R[1:]: D[i] = D[P[i]] + 1 while len(Y) <= D[i]: Y.append([]) Y[D[i]].append(i) A = [0] + [int(a) for a in input().split()] d = max(D) + 1 MI = [10 ** 9] * d MA = [0] * d for i, a in enumerate(A): MI[D[i]] = min(MI[D[i]], a) MA[D[i]] = max(MA[D[i]], a) S = [0] * N for i in Y[-1]: S[i] = max(abs(A[i] - MA[-1]), abs(A[i] - MI[-1])) for de in range(d - 1)[::-1]: abc1 = 0 abc2 = - 10 ** 9 for i in Y[de]: ma = 0 for j in X[i]: ma = max(ma, S[j]) abc1 = max(abc1, ma + A[i]);abc2 = max(abc2, ma - A[i]);S[i] = max(abs(A[i] - MI[de]), abs(MA[de] - A[i])) + ma for i in Y[de]:S[i] = max(S[i], abc1 - A[i], abc2 + A[i]) print(S[0]) ```
output
1
51,563
13
103,127
Provide tags and a correct Python 3 solution for this coding contest problem. You are given n - 1 integers a_2, ..., a_n and a tree with n vertices rooted at vertex 1. The leaves are all at the same distance d from the root. Recall that a tree is a connected undirected graph without cycles. The distance between two vertices is the number of edges on the simple path between them. All non-root vertices with degree 1 are leaves. If vertices s and f are connected by an edge and the distance of f from the root is greater than the distance of s from the root, then f is called a child of s. Initially, there are a red coin and a blue coin on the vertex 1. Let r be the vertex where the red coin is and let b be the vertex where the blue coin is. You should make d moves. A move consists of three steps: * Move the red coin to any child of r. * Move the blue coin to any vertex b' such that dist(1, b') = dist(1, b) + 1. Here dist(x, y) indicates the length of the simple path between x and y. Note that b and b' are not necessarily connected by an edge. * You can optionally swap the two coins (or skip this step). Note that r and b can be equal at any time, and there is no number written on the root. After each move, you gain |a_r - a_b| points. What's the maximum number of points you can gain after d moves? Input The first line contains a single integer t (1 ≤ t ≤ 10^4) — the number of test cases. The first line of each test case contains a single integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of vertices in the tree. The second line of each test case contains n-1 integers v_2, v_3, ..., v_n (1 ≤ v_i ≤ n, v_i ≠ i) — the i-th of them indicates that there is an edge between vertices i and v_i. It is guaranteed, that these edges form a tree. The third line of each test case contains n-1 integers a_2, ..., a_n (1 ≤ a_i ≤ 10^9) — the numbers written on the vertices. It is guaranteed that the sum of n for all test cases does not exceed 2 ⋅ 10^5. Output For each test case, print a single integer: the maximum number of points you can gain after d moves. Example Input 4 14 1 1 1 2 3 4 4 5 5 6 7 8 8 2 3 7 7 6 9 5 9 7 3 6 6 5 6 1 2 2 3 4 32 78 69 5 41 15 1 15 1 10 4 9 11 2 4 1 8 6 10 11 62 13 12 43 39 65 42 86 25 38 19 19 43 62 15 11 2 7 6 9 8 10 1 1 1 5 3 15 2 50 19 30 35 9 45 13 24 8 44 16 26 10 40 Output 14 45 163 123 Note In the first test case, an optimal solution is to: * move 1: r = 4, b = 2; no swap; * move 2: r = 7, b = 6; swap (after it r = 6, b = 7); * move 3: r = 11, b = 9; no swap. The total number of points is |7 - 2| + |6 - 9| + |3 - 9| = 14. <image> In the second test case, an optimal solution is to: * move 1: r = 2, b = 2; no swap; * move 2: r = 3, b = 4; no swap; * move 3: r = 5, b = 6; no swap. The total number of points is |32 - 32| + |78 - 69| + |5 - 41| = 45.
instruction
0
51,564
13
103,128
Tags: dfs and similar, dp, greedy, trees Correct Solution: ``` import sys input = lambda: sys.stdin.readline().rstrip() from collections import deque T = int(input()) for _ in range(T): N = int(input()) X = [[] for i in range(N)] pp = [int(a)-1 for a in input().split()] for i, p in enumerate(pp, 1): X[i].append(p) X[p].append(i) P = [-1] * N Q = deque([0]) R = [] while Q: i = deque.popleft(Q) R.append(i) for a in X[i]: if a != P[i]: P[a] = i X[a].remove(i) deque.append(Q, a) Y = [[0]] D = [0] * N for i in R[1:]: D[i] = D[P[i]] + 1 while len(Y) <= D[i]: Y.append([]) Y[D[i]].append(i) A = [0] + [int(a) for a in input().split()] d = max(D) + 1 MI = [10 ** 9] * d MA = [0] * d for i, a in enumerate(A): MI[D[i]] = min(MI[D[i]], a) MA[D[i]] = max(MA[D[i]], a) S = [0] * N for i in Y[-1]: S[i] = max(abs(A[i] - MA[-1]), abs(A[i] - MI[-1])) for de in range(d - 1)[::-1]: abc1 = 0 abc2 = - 10 ** 9 for i in Y[de]: ma = 0 for j in X[i]: ma = max(ma, S[j]) abc1 = max(abc1, ma + A[i]) abc2 = max(abc2, ma - A[i]) S[i] = max(abs(A[i] - MI[de]), abs(MA[de] - A[i])) + ma for i in Y[de]: S[i] = max(S[i], abc1 - A[i], abc2 + A[i]) print(S[0]) ```
output
1
51,564
13
103,129
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given n - 1 integers a_2, ..., a_n and a tree with n vertices rooted at vertex 1. The leaves are all at the same distance d from the root. Recall that a tree is a connected undirected graph without cycles. The distance between two vertices is the number of edges on the simple path between them. All non-root vertices with degree 1 are leaves. If vertices s and f are connected by an edge and the distance of f from the root is greater than the distance of s from the root, then f is called a child of s. Initially, there are a red coin and a blue coin on the vertex 1. Let r be the vertex where the red coin is and let b be the vertex where the blue coin is. You should make d moves. A move consists of three steps: * Move the red coin to any child of r. * Move the blue coin to any vertex b' such that dist(1, b') = dist(1, b) + 1. Here dist(x, y) indicates the length of the simple path between x and y. Note that b and b' are not necessarily connected by an edge. * You can optionally swap the two coins (or skip this step). Note that r and b can be equal at any time, and there is no number written on the root. After each move, you gain |a_r - a_b| points. What's the maximum number of points you can gain after d moves? Input The first line contains a single integer t (1 ≤ t ≤ 10^4) — the number of test cases. The first line of each test case contains a single integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of vertices in the tree. The second line of each test case contains n-1 integers v_2, v_3, ..., v_n (1 ≤ v_i ≤ n, v_i ≠ i) — the i-th of them indicates that there is an edge between vertices i and v_i. It is guaranteed, that these edges form a tree. The third line of each test case contains n-1 integers a_2, ..., a_n (1 ≤ a_i ≤ 10^9) — the numbers written on the vertices. It is guaranteed that the sum of n for all test cases does not exceed 2 ⋅ 10^5. Output For each test case, print a single integer: the maximum number of points you can gain after d moves. Example Input 4 14 1 1 1 2 3 4 4 5 5 6 7 8 8 2 3 7 7 6 9 5 9 7 3 6 6 5 6 1 2 2 3 4 32 78 69 5 41 15 1 15 1 10 4 9 11 2 4 1 8 6 10 11 62 13 12 43 39 65 42 86 25 38 19 19 43 62 15 11 2 7 6 9 8 10 1 1 1 5 3 15 2 50 19 30 35 9 45 13 24 8 44 16 26 10 40 Output 14 45 163 123 Note In the first test case, an optimal solution is to: * move 1: r = 4, b = 2; no swap; * move 2: r = 7, b = 6; swap (after it r = 6, b = 7); * move 3: r = 11, b = 9; no swap. The total number of points is |7 - 2| + |6 - 9| + |3 - 9| = 14. <image> In the second test case, an optimal solution is to: * move 1: r = 2, b = 2; no swap; * move 2: r = 3, b = 4; no swap; * move 3: r = 5, b = 6; no swap. The total number of points is |32 - 32| + |78 - 69| + |5 - 41| = 45. Submitted Solution: ``` def divisors(M): d=[] i=1 while M>=i**2: if M%i==0: d.append(i) if i**2!=M: d.append(M//i) i=i+1 return d def popcount(x): x = x - ((x >> 1) & 0x55555555) x = (x & 0x33333333) + ((x >> 2) & 0x33333333) x = (x + (x >> 4)) & 0x0f0f0f0f x = x + (x >> 8) x = x + (x >> 16) return x & 0x0000007f def eratosthenes(n): res=[0 for i in range(n+1)] prime=set([]) for i in range(2,n+1): if not res[i]: prime.add(i) for j in range(1,n//i+1): res[i*j]=1 return prime def factorization(n): res=[] for p in prime: if n%p==0: while n%p==0: n//=p res.append(p) if n!=1: res.append(n) return res def euler_phi(n): res = n for x in range(2,n+1): if x ** 2 > n: break if n%x==0: res = res//x * (x-1) while n%x==0: n //= x if n!=1: res = res//n * (n-1) return res def ind(b,n): res=0 while n%b==0: res+=1 n//=b return res def isPrimeMR(n): d = n - 1 d = d // (d & -d) L = [2, 3, 5, 7, 11, 13, 17] for a in L: t = d y = pow(a, t, n) if y == 1: continue while y != n - 1: y = (y * y) % n if y == 1 or t == n - 1: return 0 t <<= 1 return 1 def findFactorRho(n): from math import gcd m = 1 << n.bit_length() // 8 for c in range(1, 99): f = lambda x: (x * x + c) % n y, r, q, g = 2, 1, 1, 1 while g == 1: x = y for i in range(r): y = f(y) k = 0 while k < r and g == 1: ys = y for i in range(min(m, r - k)): y = f(y) q = q * abs(x - y) % n g = gcd(q, n) k += m r <<= 1 if g == n: g = 1 while g == 1: ys = f(ys) g = gcd(abs(x - ys), n) if g < n: if isPrimeMR(g): return g elif isPrimeMR(n // g): return n // g return findFactorRho(g) def primeFactor(n): i = 2 ret = {} rhoFlg = 0 while i*i <= n: k = 0 while n % i == 0: n //= i k += 1 if k: ret[i] = k i += 1 + i % 2 if i == 101 and n >= 2 ** 20: while n > 1: if isPrimeMR(n): ret[n], n = 1, 1 else: rhoFlg = 1 j = findFactorRho(n) k = 0 while n % j == 0: n //= j k += 1 ret[j] = k if n > 1: ret[n] = 1 if rhoFlg: ret = {x: ret[x] for x in sorted(ret)} return ret def divisors(n): res = [1] prime = primeFactor(n) for p in prime: newres = [] for d in res: for j in range(prime[p]+1): newres.append(d*p**j) res = newres res.sort() return res def xorfactorial(num):#排他的論理和の階乗 if num==0: return 0 elif num==1: return 1 elif num==2: return 3 elif num==3: return 0 else: x=baseorder(num) return (2**x)*((num-2**x+1)%2)+function(num-2**x) def xorconv(n,X,Y): if n==0: res=[(X[0]*Y[0])%mod] return res x=[X[i]+X[i+2**(n-1)] for i in range(2**(n-1))] y=[Y[i]+Y[i+2**(n-1)] for i in range(2**(n-1))] z=[X[i]-X[i+2**(n-1)] for i in range(2**(n-1))] w=[Y[i]-Y[i+2**(n-1)] for i in range(2**(n-1))] res1=xorconv(n-1,x,y) res2=xorconv(n-1,z,w) former=[(res1[i]+res2[i])*inv for i in range(2**(n-1))] latter=[(res1[i]-res2[i])*inv for i in range(2**(n-1))] former=list(map(lambda x:x%mod,former)) latter=list(map(lambda x:x%mod,latter)) return former+latter def merge_sort(A,B): pos_A,pos_B = 0,0 n,m = len(A),len(B) res = [] while pos_A < n and pos_B < m: a,b = A[pos_A],B[pos_B] if a < b: res.append(a) pos_A += 1 else: res.append(b) pos_B += 1 res += A[pos_A:] res += B[pos_B:] return res class UnionFindVerSize(): def __init__(self, N): self._parent = [n for n in range(0, N)] self._size = [1] * N self.group = N def find_root(self, x): if self._parent[x] == x: return x self._parent[x] = self.find_root(self._parent[x]) stack = [x] while self._parent[stack[-1]]!=stack[-1]: stack.append(self._parent[stack[-1]]) for v in stack: self._parent[v] = stack[-1] return self._parent[x] def unite(self, x, y): gx = self.find_root(x) gy = self.find_root(y) if gx == gy: return self.group -= 1 if self._size[gx] < self._size[gy]: self._parent[gx] = gy self._size[gy] += self._size[gx] else: self._parent[gy] = gx self._size[gx] += self._size[gy] def get_size(self, x): return self._size[self.find_root(x)] def is_same_group(self, x, y): return self.find_root(x) == self.find_root(y) class WeightedUnionFind(): def __init__(self,N): self.parent = [i for i in range(N)] self.size = [1 for i in range(N)] self.val = [0 for i in range(N)] self.flag = True self.edge = [[] for i in range(N)] def dfs(self,v,pv): stack = [(v,pv)] new_parent = self.parent[pv] while stack: v,pv = stack.pop() self.parent[v] = new_parent for nv,w in self.edge[v]: if nv!=pv: self.val[nv] = self.val[v] + w stack.append((nv,v)) def unite(self,x,y,w): if not self.flag: return if self.parent[x]==self.parent[y]: self.flag = (self.val[x] - self.val[y] == w) return if self.size[self.parent[x]]>self.size[self.parent[y]]: self.edge[x].append((y,-w)) self.edge[y].append((x,w)) self.size[x] += self.size[y] self.val[y] = self.val[x] - w self.dfs(y,x) else: self.edge[x].append((y,-w)) self.edge[y].append((x,w)) self.size[y] += self.size[x] self.val[x] = self.val[y] + w self.dfs(x,y) class Dijkstra(): class Edge(): def __init__(self, _to, _cost): self.to = _to self.cost = _cost def __init__(self, V): self.G = [[] for i in range(V)] self._E = 0 self._V = V @property def E(self): return self._E @property def V(self): return self._V def add_edge(self, _from, _to, _cost): self.G[_from].append(self.Edge(_to, _cost)) self._E += 1 def shortest_path(self, s): import heapq que = [] d = [10**15] * self.V d[s] = 0 heapq.heappush(que, (0, s)) while len(que) != 0: cost, v = heapq.heappop(que) if d[v] < cost: continue for i in range(len(self.G[v])): e = self.G[v][i] if d[e.to] > d[v] + e.cost: d[e.to] = d[v] + e.cost heapq.heappush(que, (d[e.to], e.to)) return d #Z[i]:length of the longest list starting from S[i] which is also a prefix of S #O(|S|) def Z_algorithm(s): N = len(s) Z_alg = [0]*N Z_alg[0] = N i = 1 j = 0 while i < N: while i+j < N and s[j] == s[i+j]: j += 1 Z_alg[i] = j if j == 0: i += 1 continue k = 1 while i+k < N and k + Z_alg[k]<j: Z_alg[i+k] = Z_alg[k] k += 1 i += k j -= k return Z_alg class BIT(): def __init__(self,n): self.BIT=[0]*(n+1) self.num=n def query(self,idx): res_sum = 0 while idx > 0: res_sum += self.BIT[idx] idx -= idx&(-idx) return res_sum #Ai += x O(logN) def update(self,idx,x): while idx <= self.num: self.BIT[idx] += x idx += idx&(-idx) return class dancinglink(): def __init__(self,n,debug=False): self.n = n self.debug = debug self._left = [i-1 for i in range(n)] self._right = [i+1 for i in range(n)] self.exist = [True for i in range(n)] def pop(self,k): if self.debug: assert self.exist[k] L = self._left[k] R = self._right[k] if L!=-1: if R!=self.n: self._right[L],self._left[R] = R,L else: self._right[L] = self.n elif R!=self.n: self._left[R] = -1 self.exist[k] = False def left(self,idx,k=1): if self.debug: assert self.exist[idx] res = idx while k: res = self._left[res] if res==-1: break k -= 1 return res def right(self,idx,k=1): if self.debug: assert self.exist[idx] res = idx while k: res = self._right[res] if res==self.n: break k -= 1 return res class SparseTable(): def __init__(self,A,merge_func,ide_ele): N=len(A) n=N.bit_length() self.table=[[ide_ele for i in range(n)] for i in range(N)] self.merge_func=merge_func for i in range(N): self.table[i][0]=A[i] for j in range(1,n): for i in range(0,N-2**j+1): f=self.table[i][j-1] s=self.table[i+2**(j-1)][j-1] self.table[i][j]=self.merge_func(f,s) def query(self,s,t): b=t-s+1 m=b.bit_length()-1 return self.merge_func(self.table[s][m],self.table[t-2**m+1][m]) class BinaryTrie: class node: def __init__(self,val): self.left = None self.right = None self.max = val def __init__(self): self.root = self.node(-10**15) def append(self,key,val): pos = self.root for i in range(29,-1,-1): pos.max = max(pos.max,val) if key>>i & 1: if pos.right is None: pos.right = self.node(val) pos = pos.right else: pos = pos.right else: if pos.left is None: pos.left = self.node(val) pos = pos.left else: pos = pos.left pos.max = max(pos.max,val) def search(self,M,xor): res = -10**15 pos = self.root for i in range(29,-1,-1): if pos is None: break if M>>i & 1: if xor>>i & 1: if pos.right: res = max(res,pos.right.max) pos = pos.left else: if pos.left: res = max(res,pos.left.max) pos = pos.right else: if xor>>i & 1: pos = pos.right else: pos = pos.left if pos: res = max(res,pos.max) return res def solveequation(edge,ans,n,m): #edge=[[to,dire,id]...] x=[0]*m used=[False]*n for v in range(n): if used[v]: continue y = dfs(v) if y!=0: return False return x def dfs(v): used[v]=True r=ans[v] for to,dire,id in edge[v]: if used[to]: continue y=dfs(to) if dire==-1: x[id]=y else: x[id]=-y r+=y return r class Matrix(): mod=10**9+7 def set_mod(m): Matrix.mod=m def __init__(self,L): self.row=len(L) self.column=len(L[0]) self._matrix=L for i in range(self.row): for j in range(self.column): self._matrix[i][j]%=Matrix.mod def __getitem__(self,item): if type(item)==int: raise IndexError("you must specific row and column") elif len(item)!=2: raise IndexError("you must specific row and column") i,j=item return self._matrix[i][j] def __setitem__(self,item,val): if type(item)==int: raise IndexError("you must specific row and column") elif len(item)!=2: raise IndexError("you must specific row and column") i,j=item self._matrix[i][j]=val def __add__(self,other): if (self.row,self.column)!=(other.row,other.column): raise SizeError("sizes of matrixes are different") res=[[0 for j in range(self.column)] for i in range(self.row)] for i in range(self.row): for j in range(self.column): res[i][j]=self._matrix[i][j]+other._matrix[i][j] res[i][j]%=Matrix.mod return Matrix(res) def __sub__(self,other): if (self.row,self.column)!=(other.row,other.column): raise SizeError("sizes of matrixes are different") res=[[0 for j in range(self.column)] for i in range(self.row)] for i in range(self.row): for j in range(self.column): res[i][j]=self._matrix[i][j]-other._matrix[i][j] res[i][j]%=Matrix.mod return Matrix(res) def __mul__(self,other): if type(other)!=int: if self.column!=other.row: raise SizeError("sizes of matrixes are different") res=[[0 for j in range(other.column)] for i in range(self.row)] for i in range(self.row): for j in range(other.column): temp=0 for k in range(self.column): temp+=self._matrix[i][k]*other._matrix[k][j] res[i][j]=temp%Matrix.mod return Matrix(res) else: n=other res=[[(n*self._matrix[i][j])%Matrix.mod for j in range(self.column)] for i in range(self.row)] return Matrix(res) def __pow__(self,m): if self.column!=self.row: raise MatrixPowError("the size of row must be the same as that of column") n=self.row res=Matrix([[int(i==j) for i in range(n)] for j in range(n)]) while m: if m%2==1: res=res*self self=self*self m//=2 return res def __str__(self): res=[] for i in range(self.row): for j in range(self.column): res.append(str(self._matrix[i][j])) res.append(" ") res.append("\n") res=res[:len(res)-1] return "".join(res) class SegmentTree: def __init__(self, init_val, segfunc, ide_ele): n = len(init_val) self.segfunc = segfunc self.ide_ele = ide_ele self.num = 1 << (n - 1).bit_length() self.tree = [ide_ele] * 2 * self.num for i in range(n): self.tree[self.num + i] = init_val[i] for i in range(self.num - 1, 0, -1): self.tree[i] = self.segfunc(self.tree[2 * i], self.tree[2 * i + 1]) def update(self, k, x): k += self.num self.tree[k] = x while k > 1: self.tree[k >> 1] = self.segfunc(self.tree[k], self.tree[k ^ 1]) k >>= 1 def query(self, l, r): res = self.ide_ele l += self.num r += self.num while l < r: if l & 1: res = self.segfunc(res, self.tree[l]) l += 1 if r & 1: res = self.segfunc(res, self.tree[r - 1]) l >>= 1 r >>= 1 return res def bisect_l(self,l,r,x): l += self.num r += self.num Lmin = -1 Rmin = -1 while l<r: if l & 1: if self.tree[l] <= x and Lmin==-1: Lmin = l l += 1 if r & 1: if self.tree[r-1] <=x: Rmin = r-1 l >>= 1 r >>= 1 if Lmin != -1: pos = Lmin while pos<self.num: if self.tree[2 * pos] <=x: pos = 2 * pos else: pos = 2 * pos +1 return pos-self.num elif Rmin != -1: pos = Rmin while pos<self.num: if self.tree[2 * pos] <=x: pos = 2 * pos else: pos = 2 * pos +1 return pos-self.num else: return -1 from heapq import heappush, heappop class MinCostFlow: INF = 10**18 def __init__(self, N): self.N = N self.G = [[] for i in range(N)] def add_edge(self, fr, to, cap, cost): forward = [to, cap, cost, None] backward = forward[3] = [fr, 0, -cost, forward] self.G[fr].append(forward) self.G[to].append(backward) def flow(self, s, t, f): N = self.N; G = self.G INF = MinCostFlow.INF res = 0 H = [0]*N prv_v = [0]*N prv_e = [None]*N d0 = [INF]*N dist = [INF]*N while f: dist[:] = d0 dist[s] = 0 que = [(0, s)] while que: c, v = heappop(que) if dist[v] < c: continue r0 = dist[v] + H[v] for e in G[v]: w, cap, cost, _ = e if cap > 0 and r0 + cost - H[w] < dist[w]: dist[w] = r = r0 + cost - H[w] prv_v[w] = v; prv_e[w] = e heappush(que, (r, w)) if dist[t] == INF: return None for i in range(N): H[i] += dist[i] d = f; v = t while v != s: d = min(d, prv_e[v][1]) v = prv_v[v] f -= d res += d * H[t] v = t while v != s: e = prv_e[v] e[1] -= d e[3][1] += d v = prv_v[v] return res import sys,random,bisect from collections import deque,defaultdict from heapq import heapify,heappop,heappush from itertools import permutations from math import log,gcd input = lambda :sys.stdin.readline().rstrip() mi = lambda :map(int,input().split()) li = lambda :list(mi()) ans = [] for _ in range(int(input())): n = int(input()) p = [-1] + [int(u)-1 for u in input().split()] a = [0] + li() edge = [[] for i in range(n)] for i in range(1,n): u,v = i,p[i] edge[u].append(v) edge[v].append(u) deq = deque([0]) parent = [-1 for i in range(n)] depth = [0 for i in range(n)] depth_max = [0 for i in range(n)] depth_min = [10**18 for i in range(n)] res = [] while deq: v = deq.popleft() res.append(v) for nv in edge[v]: if nv!=parent[v]: parent[nv] = v depth[nv] = depth[v] + 1 depth_max[depth[nv]] = max(depth_max[depth[nv]],a[nv]) depth_min[depth[nv]] = min(depth_min[depth[nv]],a[nv]) deq.append(nv) dp = [0 for i in range(n)] depth_max_plus = [-10**17 for i in range(n)] depth_max_minus = [-10**17 for i in range(n)] for v in res[::-1]: edge[v] = [nv for nv in edge[v] if nv!=parent[v]] if not edge[v]: continue for nv in edge[v]: d = depth[nv] dp[v] = max(dp[v],dp[nv]+depth_max[d]-a[nv],dp[nv]+a[nv]-depth_min[d]) dp[v] = max(dp[v],depth_max_minus[d]+a[nv],depth_max_plus[d]-a[nv]) d = depth[v] #print(dp[v],) depth_max_plus[d] = max(depth_max_plus[d],dp[v]+a[v]) depth_max_minus[d] = max(depth_max_minus[d],dp[v]-a[v]) ans.append(dp[0]) print(*ans,sep="\n") ```
instruction
0
51,565
13
103,130
Yes
output
1
51,565
13
103,131
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given n - 1 integers a_2, ..., a_n and a tree with n vertices rooted at vertex 1. The leaves are all at the same distance d from the root. Recall that a tree is a connected undirected graph without cycles. The distance between two vertices is the number of edges on the simple path between them. All non-root vertices with degree 1 are leaves. If vertices s and f are connected by an edge and the distance of f from the root is greater than the distance of s from the root, then f is called a child of s. Initially, there are a red coin and a blue coin on the vertex 1. Let r be the vertex where the red coin is and let b be the vertex where the blue coin is. You should make d moves. A move consists of three steps: * Move the red coin to any child of r. * Move the blue coin to any vertex b' such that dist(1, b') = dist(1, b) + 1. Here dist(x, y) indicates the length of the simple path between x and y. Note that b and b' are not necessarily connected by an edge. * You can optionally swap the two coins (or skip this step). Note that r and b can be equal at any time, and there is no number written on the root. After each move, you gain |a_r - a_b| points. What's the maximum number of points you can gain after d moves? Input The first line contains a single integer t (1 ≤ t ≤ 10^4) — the number of test cases. The first line of each test case contains a single integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of vertices in the tree. The second line of each test case contains n-1 integers v_2, v_3, ..., v_n (1 ≤ v_i ≤ n, v_i ≠ i) — the i-th of them indicates that there is an edge between vertices i and v_i. It is guaranteed, that these edges form a tree. The third line of each test case contains n-1 integers a_2, ..., a_n (1 ≤ a_i ≤ 10^9) — the numbers written on the vertices. It is guaranteed that the sum of n for all test cases does not exceed 2 ⋅ 10^5. Output For each test case, print a single integer: the maximum number of points you can gain after d moves. Example Input 4 14 1 1 1 2 3 4 4 5 5 6 7 8 8 2 3 7 7 6 9 5 9 7 3 6 6 5 6 1 2 2 3 4 32 78 69 5 41 15 1 15 1 10 4 9 11 2 4 1 8 6 10 11 62 13 12 43 39 65 42 86 25 38 19 19 43 62 15 11 2 7 6 9 8 10 1 1 1 5 3 15 2 50 19 30 35 9 45 13 24 8 44 16 26 10 40 Output 14 45 163 123 Note In the first test case, an optimal solution is to: * move 1: r = 4, b = 2; no swap; * move 2: r = 7, b = 6; swap (after it r = 6, b = 7); * move 3: r = 11, b = 9; no swap. The total number of points is |7 - 2| + |6 - 9| + |3 - 9| = 14. <image> In the second test case, an optimal solution is to: * move 1: r = 2, b = 2; no swap; * move 2: r = 3, b = 4; no swap; * move 3: r = 5, b = 6; no swap. The total number of points is |32 - 32| + |78 - 69| + |5 - 41| = 45. Submitted Solution: ``` import sys, io, os from collections import defaultdict if os.environ['USERNAME']=='kissz': inp=open('in1.txt','r').readline def debug(*args): print(*args,file=sys.stderr) else: inp=io.BytesIO(os.read(0,os.fstat(0).st_size)).readline def debug(*args): pass # SCRIPT STARTS HERE for _ in range(int(inp())): n=int(inp()) parents=[0,0]+[*map(int,inp().split())] depth=[-1]*(n+1) depth[1]=0 layers=defaultdict(list) children=defaultdict(list) for i in range(2,n+1): children[parents[i]].append(i) val=[0,0]+[*map(int,inp().split())] layer_mins=[1<<30]*(n+1) layer_maxs=[0]*(n+1) maxdepth=0 Q=children[1] while Q: i=Q.pop() p=parents[i] d=depth[p]+1 depth[i]=d maxdepth=max(maxdepth,d) layer_mins[d]=min(layer_mins[d],val[i]) layer_maxs[d]=max(layer_maxs[d],val[i]) layers[depth[i]].append(i) Q+=children[i] best=[0]*(n+1) for d in range(1,maxdepth+1): best_sub=max(best[parents[i]]-val[i] for i in layers[d]) best_add=max(best[parents[i]]+val[i] for i in layers[d]) for i in layers[d]: best[i]=max(best[parents[i]]+layer_maxs[d]-val[i], best[parents[i]]+val[i]-layer_mins[d], val[i]+best_sub, best_add-val[i]) #debug(i,best[parents[i]]+layer_maxs[d]-val[i], # best[parents[i]]+val[i]-layer_mins[d], # val[i]+best_sub, # best_add-val[i]) print(max(best)) ```
instruction
0
51,566
13
103,132
Yes
output
1
51,566
13
103,133
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given n - 1 integers a_2, ..., a_n and a tree with n vertices rooted at vertex 1. The leaves are all at the same distance d from the root. Recall that a tree is a connected undirected graph without cycles. The distance between two vertices is the number of edges on the simple path between them. All non-root vertices with degree 1 are leaves. If vertices s and f are connected by an edge and the distance of f from the root is greater than the distance of s from the root, then f is called a child of s. Initially, there are a red coin and a blue coin on the vertex 1. Let r be the vertex where the red coin is and let b be the vertex where the blue coin is. You should make d moves. A move consists of three steps: * Move the red coin to any child of r. * Move the blue coin to any vertex b' such that dist(1, b') = dist(1, b) + 1. Here dist(x, y) indicates the length of the simple path between x and y. Note that b and b' are not necessarily connected by an edge. * You can optionally swap the two coins (or skip this step). Note that r and b can be equal at any time, and there is no number written on the root. After each move, you gain |a_r - a_b| points. What's the maximum number of points you can gain after d moves? Input The first line contains a single integer t (1 ≤ t ≤ 10^4) — the number of test cases. The first line of each test case contains a single integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of vertices in the tree. The second line of each test case contains n-1 integers v_2, v_3, ..., v_n (1 ≤ v_i ≤ n, v_i ≠ i) — the i-th of them indicates that there is an edge between vertices i and v_i. It is guaranteed, that these edges form a tree. The third line of each test case contains n-1 integers a_2, ..., a_n (1 ≤ a_i ≤ 10^9) — the numbers written on the vertices. It is guaranteed that the sum of n for all test cases does not exceed 2 ⋅ 10^5. Output For each test case, print a single integer: the maximum number of points you can gain after d moves. Example Input 4 14 1 1 1 2 3 4 4 5 5 6 7 8 8 2 3 7 7 6 9 5 9 7 3 6 6 5 6 1 2 2 3 4 32 78 69 5 41 15 1 15 1 10 4 9 11 2 4 1 8 6 10 11 62 13 12 43 39 65 42 86 25 38 19 19 43 62 15 11 2 7 6 9 8 10 1 1 1 5 3 15 2 50 19 30 35 9 45 13 24 8 44 16 26 10 40 Output 14 45 163 123 Note In the first test case, an optimal solution is to: * move 1: r = 4, b = 2; no swap; * move 2: r = 7, b = 6; swap (after it r = 6, b = 7); * move 3: r = 11, b = 9; no swap. The total number of points is |7 - 2| + |6 - 9| + |3 - 9| = 14. <image> In the second test case, an optimal solution is to: * move 1: r = 2, b = 2; no swap; * move 2: r = 3, b = 4; no swap; * move 3: r = 5, b = 6; no swap. The total number of points is |32 - 32| + |78 - 69| + |5 - 41| = 45. Submitted Solution: ``` from collections import deque T = int(input()) def solve(E, W): nodes = {idx: (w, []) for idx, w in weights.items()} for u, v in E: nodes[u][1].append(v) nodes[v][1].append(u) layers = [] visited = set([1]) parents = {idx: None for idx in weights.keys()} Q = deque([1]) while Q: layers.append(list(Q)) l = len(Q) for _ in range(l): cur_idx = Q.popleft() for v in nodes[cur_idx][1]: if v not in visited: Q.append(v) visited.add(v) parents[v] = cur_idx dp_b = {idx: 0 for idx in weights.keys()} dp_r = {idx: 0 for idx in weights.keys()} for l in range(1, len(layers)): max_w = max([nodes[idx][0] for idx in layers[l]]) min_w = min([nodes[idx][0] for idx in layers[l]]) for u in layers[l]: p = parents[u] dp_r[u] = max( dp_r[p] + max(nodes[u][0] - min_w, max_w - nodes[u][0]), dp_b[p] + max(nodes[u][0] - min_w, max_w - nodes[u][0]) ) for v in layers[l]: pv = parents[v] dp_b[u] = max(dp_b[u], dp_r[pv] + abs(nodes[u][0] - nodes[v][0])) # print('layers: {}'.format(layers)) # print('dp: {}'.format(dp_r)) return max([dp_r[idx] for idx in layers[-1]] + [dp_b[idx] for idx in layers[-1]]) for _ in range(T): n = int(input()) V = list(map(int, input().split(' '))) W = list(map(int, input().split(' '))) edges = [] weights = {1: 0} for i in range(n-1): edges.append((i+2, V[i])) for i in range(n-1): weights[i+2] = W[i] print(solve(edges, weights)) ```
instruction
0
51,567
13
103,134
No
output
1
51,567
13
103,135
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given n - 1 integers a_2, ..., a_n and a tree with n vertices rooted at vertex 1. The leaves are all at the same distance d from the root. Recall that a tree is a connected undirected graph without cycles. The distance between two vertices is the number of edges on the simple path between them. All non-root vertices with degree 1 are leaves. If vertices s and f are connected by an edge and the distance of f from the root is greater than the distance of s from the root, then f is called a child of s. Initially, there are a red coin and a blue coin on the vertex 1. Let r be the vertex where the red coin is and let b be the vertex where the blue coin is. You should make d moves. A move consists of three steps: * Move the red coin to any child of r. * Move the blue coin to any vertex b' such that dist(1, b') = dist(1, b) + 1. Here dist(x, y) indicates the length of the simple path between x and y. Note that b and b' are not necessarily connected by an edge. * You can optionally swap the two coins (or skip this step). Note that r and b can be equal at any time, and there is no number written on the root. After each move, you gain |a_r - a_b| points. What's the maximum number of points you can gain after d moves? Input The first line contains a single integer t (1 ≤ t ≤ 10^4) — the number of test cases. The first line of each test case contains a single integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of vertices in the tree. The second line of each test case contains n-1 integers v_2, v_3, ..., v_n (1 ≤ v_i ≤ n, v_i ≠ i) — the i-th of them indicates that there is an edge between vertices i and v_i. It is guaranteed, that these edges form a tree. The third line of each test case contains n-1 integers a_2, ..., a_n (1 ≤ a_i ≤ 10^9) — the numbers written on the vertices. It is guaranteed that the sum of n for all test cases does not exceed 2 ⋅ 10^5. Output For each test case, print a single integer: the maximum number of points you can gain after d moves. Example Input 4 14 1 1 1 2 3 4 4 5 5 6 7 8 8 2 3 7 7 6 9 5 9 7 3 6 6 5 6 1 2 2 3 4 32 78 69 5 41 15 1 15 1 10 4 9 11 2 4 1 8 6 10 11 62 13 12 43 39 65 42 86 25 38 19 19 43 62 15 11 2 7 6 9 8 10 1 1 1 5 3 15 2 50 19 30 35 9 45 13 24 8 44 16 26 10 40 Output 14 45 163 123 Note In the first test case, an optimal solution is to: * move 1: r = 4, b = 2; no swap; * move 2: r = 7, b = 6; swap (after it r = 6, b = 7); * move 3: r = 11, b = 9; no swap. The total number of points is |7 - 2| + |6 - 9| + |3 - 9| = 14. <image> In the second test case, an optimal solution is to: * move 1: r = 2, b = 2; no swap; * move 2: r = 3, b = 4; no swap; * move 3: r = 5, b = 6; no swap. The total number of points is |32 - 32| + |78 - 69| + |5 - 41| = 45. Submitted Solution: ``` from collections import deque T = int(input()) def solve(E, W): nodes = {idx: (w, []) for idx, w in weights.items()} for u, v in E: nodes[u][1].append(v) nodes[v][1].append(u) layers = [] visited = set([1]) parents = {idx: None for idx in weights.keys()} Q = deque([1]) while Q: layers.append(list(Q)) l = len(Q) for _ in range(l): cur_idx = Q.popleft() for v in nodes[cur_idx][1]: if v not in visited: Q.append(v) visited.add(v) parents[v] = cur_idx dp_b = {idx: 0 for idx in weights.keys()} dp_r = {idx: 0 for idx in weights.keys()} for l in range(1, len(layers)): max_w = max([nodes[idx][0] for idx in layers[l]]) min_w = min([nodes[idx][0] for idx in layers[l]]) for u in layers[l]: p = parents[u] dp_r[u] = max( dp_r[p] + max(nodes[u][0] - min_w, max_w - nodes[u][0]), dp_b[p] + max(nodes[u][0] - min_w, max_w - nodes[u][0]) ) for v in layers[l]: pv = parents[v] dp_b[u] = max(dp_b[u], dp_r[pv] + abs(nodes[u][0] - nodes[v][0])) # print('layers: {}'.format(layers)) # print('dp: {}'.format(dp_r)) return max([dp_r[idx] for idx in layers[-1]]) for _ in range(T): n = int(input()) V = list(map(int, input().split(' '))) W = list(map(int, input().split(' '))) edges = [] weights = {1: 0} for i in range(n-1): edges.append((i+2, V[i])) for i in range(n-1): weights[i+2] = W[i] print(solve(edges, weights)) ```
instruction
0
51,568
13
103,136
No
output
1
51,568
13
103,137
Provide tags and a correct Python 3 solution for this coding contest problem. Alyona decided to go on a diet and went to the forest to get some apples. There she unexpectedly found a magic rooted tree with root in the vertex 1, every vertex and every edge of which has a number written on. The girl noticed that some of the tree's vertices are sad, so she decided to play with them. Let's call vertex v sad if there is a vertex u in subtree of vertex v such that dist(v, u) > au, where au is the number written on vertex u, dist(v, u) is the sum of the numbers written on the edges on the path from v to u. Leaves of a tree are vertices connected to a single vertex by a single edge, but the root of a tree is a leaf if and only if the tree consists of a single vertex — root. Thus Alyona decided to remove some of tree leaves until there will be no any sad vertex left in the tree. What is the minimum number of leaves Alyona needs to remove? Input In the first line of the input integer n (1 ≤ n ≤ 105) is given — the number of vertices in the tree. In the second line the sequence of n integers a1, a2, ..., an (1 ≤ ai ≤ 109) is given, where ai is the number written on vertex i. The next n - 1 lines describe tree edges: ith of them consists of two integers pi and ci (1 ≤ pi ≤ n, - 109 ≤ ci ≤ 109), meaning that there is an edge connecting vertices i + 1 and pi with number ci written on it. Output Print the only integer — the minimum number of leaves Alyona needs to remove such that there will be no any sad vertex left in the tree. Example Input 9 88 22 83 14 95 91 98 53 11 3 24 7 -8 1 67 1 64 9 65 5 12 6 -80 3 8 Output 5 Note The following image represents possible process of removing leaves from the tree: <image>
instruction
0
51,757
13
103,514
Tags: dfs and similar, dp, graphs, trees Correct Solution: ``` from collections import deque n = int(input()) val = [0] + [int(i) for i in input().split(' ')] highest_dist = [0]*(n+1) g = [[]for i in range(n+1)] for i in range(2,n+1): a,b = map(int, input().split(' ')) g[a].append((i,b)) pilha = deque([1]) while pilha: v = pilha.pop() for u,d in g[v]: highest_dist[u] = max(d,highest_dist[v]+d) pilha.append(u) res = 0 retira = [False]*(n+1) pilha = deque([1]) while pilha: v = pilha.pop() if retira[v]: res += 1 for u,d in g[v]: highest_dist[u] = max(d,highest_dist[v]+d) if highest_dist[u] > val[u]: retira[u]=True else: retira[u] = retira[v] pilha.append(u) print(res) ```
output
1
51,757
13
103,515
Provide tags and a correct Python 3 solution for this coding contest problem. Alyona decided to go on a diet and went to the forest to get some apples. There she unexpectedly found a magic rooted tree with root in the vertex 1, every vertex and every edge of which has a number written on. The girl noticed that some of the tree's vertices are sad, so she decided to play with them. Let's call vertex v sad if there is a vertex u in subtree of vertex v such that dist(v, u) > au, where au is the number written on vertex u, dist(v, u) is the sum of the numbers written on the edges on the path from v to u. Leaves of a tree are vertices connected to a single vertex by a single edge, but the root of a tree is a leaf if and only if the tree consists of a single vertex — root. Thus Alyona decided to remove some of tree leaves until there will be no any sad vertex left in the tree. What is the minimum number of leaves Alyona needs to remove? Input In the first line of the input integer n (1 ≤ n ≤ 105) is given — the number of vertices in the tree. In the second line the sequence of n integers a1, a2, ..., an (1 ≤ ai ≤ 109) is given, where ai is the number written on vertex i. The next n - 1 lines describe tree edges: ith of them consists of two integers pi and ci (1 ≤ pi ≤ n, - 109 ≤ ci ≤ 109), meaning that there is an edge connecting vertices i + 1 and pi with number ci written on it. Output Print the only integer — the minimum number of leaves Alyona needs to remove such that there will be no any sad vertex left in the tree. Example Input 9 88 22 83 14 95 91 98 53 11 3 24 7 -8 1 67 1 64 9 65 5 12 6 -80 3 8 Output 5 Note The following image represents possible process of removing leaves from the tree: <image>
instruction
0
51,758
13
103,516
Tags: dfs and similar, dp, graphs, trees Correct Solution: ``` read = lambda: map(int, input().split()) n = int(input()) a = [0] + list(read()) g = [list() for i in range(n + 1)] for i in range(2, n + 1): p, c = read() g[i].append((p, c)) g[p].append((i, c)) was = [0] * (n + 1) st = [(1, 0, 0)] while st: v, mind, dist = st.pop() was[v] = 1 for u, c in g[v]: if not was[u]: if dist + c - min(dist + c, mind) <= a[u]: st.append((u, min(mind, dist + c), dist + c)) ans = n - was.count(1) print(ans) ```
output
1
51,758
13
103,517
Provide tags and a correct Python 3 solution for this coding contest problem. Alyona decided to go on a diet and went to the forest to get some apples. There she unexpectedly found a magic rooted tree with root in the vertex 1, every vertex and every edge of which has a number written on. The girl noticed that some of the tree's vertices are sad, so she decided to play with them. Let's call vertex v sad if there is a vertex u in subtree of vertex v such that dist(v, u) > au, where au is the number written on vertex u, dist(v, u) is the sum of the numbers written on the edges on the path from v to u. Leaves of a tree are vertices connected to a single vertex by a single edge, but the root of a tree is a leaf if and only if the tree consists of a single vertex — root. Thus Alyona decided to remove some of tree leaves until there will be no any sad vertex left in the tree. What is the minimum number of leaves Alyona needs to remove? Input In the first line of the input integer n (1 ≤ n ≤ 105) is given — the number of vertices in the tree. In the second line the sequence of n integers a1, a2, ..., an (1 ≤ ai ≤ 109) is given, where ai is the number written on vertex i. The next n - 1 lines describe tree edges: ith of them consists of two integers pi and ci (1 ≤ pi ≤ n, - 109 ≤ ci ≤ 109), meaning that there is an edge connecting vertices i + 1 and pi with number ci written on it. Output Print the only integer — the minimum number of leaves Alyona needs to remove such that there will be no any sad vertex left in the tree. Example Input 9 88 22 83 14 95 91 98 53 11 3 24 7 -8 1 67 1 64 9 65 5 12 6 -80 3 8 Output 5 Note The following image represents possible process of removing leaves from the tree: <image>
instruction
0
51,759
13
103,518
Tags: dfs and similar, dp, graphs, trees Correct Solution: ``` from sys import * setrecursionlimit(1000001) n=int(input()) a=[0]+list(map(int,input().split())) E=[[] for _ in range(n+1)] k=[1]*(n+1) for i in range(n-1): p,c=map(int,input().split()) E[i+2]+=[(p,c)] E[p]+=[(i+2,c)] def bfs(nom,pre=0): ch,ii=[(nom,pre)],0 while ii<len(ch): nom,pre=ch[ii] for x,c in E[nom]: if x!=pre: ch+=[(x,nom)] ii+=1 for i in range(len(ch)-1,-1,-1): nom,pre=ch[i] for x,c in E[nom]: if x!=pre: k[nom]+=k[x] bfs(1) def bfs2(nom,pre=0,l=0): ch=[(nom,pre,l)] ans=0 while ch!=[]: nom,pre,l=ch.pop() if l>a[nom]: ans+=k[nom]; continue for x,c in E[nom]: if x!=pre: ch+=[(x,nom,max(l+c,c))] return ans print(bfs2(1)) ```
output
1
51,759
13
103,519
Provide tags and a correct Python 3 solution for this coding contest problem. Alyona decided to go on a diet and went to the forest to get some apples. There she unexpectedly found a magic rooted tree with root in the vertex 1, every vertex and every edge of which has a number written on. The girl noticed that some of the tree's vertices are sad, so she decided to play with them. Let's call vertex v sad if there is a vertex u in subtree of vertex v such that dist(v, u) > au, where au is the number written on vertex u, dist(v, u) is the sum of the numbers written on the edges on the path from v to u. Leaves of a tree are vertices connected to a single vertex by a single edge, but the root of a tree is a leaf if and only if the tree consists of a single vertex — root. Thus Alyona decided to remove some of tree leaves until there will be no any sad vertex left in the tree. What is the minimum number of leaves Alyona needs to remove? Input In the first line of the input integer n (1 ≤ n ≤ 105) is given — the number of vertices in the tree. In the second line the sequence of n integers a1, a2, ..., an (1 ≤ ai ≤ 109) is given, where ai is the number written on vertex i. The next n - 1 lines describe tree edges: ith of them consists of two integers pi and ci (1 ≤ pi ≤ n, - 109 ≤ ci ≤ 109), meaning that there is an edge connecting vertices i + 1 and pi with number ci written on it. Output Print the only integer — the minimum number of leaves Alyona needs to remove such that there will be no any sad vertex left in the tree. Example Input 9 88 22 83 14 95 91 98 53 11 3 24 7 -8 1 67 1 64 9 65 5 12 6 -80 3 8 Output 5 Note The following image represents possible process of removing leaves from the tree: <image>
instruction
0
51,760
13
103,520
Tags: dfs and similar, dp, graphs, trees Correct Solution: ``` import sys input = sys.stdin.readline from collections import deque class Graph(object): """docstring for Graph""" def __init__(self,n,d): # Number of nodes and d is True if directed self.n = n self.graph = [[] for i in range(n)] self.parent = [-1 for i in range(n)] self.directed = d def addEdge(self,x,y): self.graph[x].append(y) if not self.directed: self.graph[y].append(x) def bfs(self, root): # NORMAL BFS queue = [root] queue = deque(queue) vis = [0]*self.n while len(queue)!=0: element = queue.popleft() vis[element] = 1 for i in self.graph[element]: if vis[i]==0: queue.append(i) self.parent[i] = element vis[i] = 1 dist[i] = dist[element] + w[(element,i)] def bfs2(self, root): # NORMAL BFS queue = [root] queue = deque(queue) vis = [0]*self.n while len(queue)!=0: element = queue.popleft() vis[element] = 1 for i in self.graph[element]: if vis[i]==0: queue.append(i) self.parent[i] = element vis[i] = 1 minn[i] = min(minn[element], dist[i]) def bfs3(self, root): # NORMAL BFS queue = [root] queue = deque(queue) vis = [0]*self.n count = 0 while len(queue)!=0: element = queue.popleft() vis[element] = 1 count += 1 for i in self.graph[element]: if vis[i]==0 and remove[i]==0: queue.append(i) self.parent[i] = element vis[i] = 1 return count def dfs(self, root, ans): # Iterative DFS stack=[root] vis=[0]*self.n stack2=[] while len(stack)!=0: # INITIAL TRAVERSAL element = stack.pop() if vis[element]: continue vis[element] = 1 stack2.append(element) for i in self.graph[element]: if vis[i]==0: self.parent[i] = element stack.append(i) while len(stack2)!=0: # BACKTRACING. Modify the loop according to the question element = stack2.pop() m = 0 for i in self.graph[element]: if i!=self.parent[element]: m += ans[i] ans[element] = m return ans def shortestpath(self, source, dest): # Calculate Shortest Path between two nodes self.bfs(source) path = [dest] while self.parent[path[-1]]!=-1: path.append(parent[path[-1]]) return path[::-1] def detect_cycle(self): indeg = [0]*self.n for i in range(self.n): for j in self.graph[i]: indeg[j] += 1 q = deque() vis = 0 for i in range(self.n): if indeg[i]==0: q.append(i) while len(q)!=0: e = q.popleft() vis += 1 for i in self.graph[e]: indeg[i] -= 1 if indeg[i]==0: q.append(i) if vis!=self.n: return True return False def reroot(self, root, ans): stack = [root] vis = [0]*n while len(stack)!=0: e = stack[-1] if vis[e]: stack.pop() # Reverse_The_Change() continue vis[e] = 1 for i in graph[e]: if not vis[e]: stack.append(i) if self.parent[e]==-1: continue # Change_The_Answers() n = int(input()) a = list(map(int,input().split())) g = Graph(n,False) w = {} for i in range(n-1): x,y = map(int,input().split()) w[(i+1,x-1)] = y w[(x-1,i+1)] = y g.addEdge(i+1,x-1) dist = [0]*n minn = [0]*n g.bfs(0) g.bfs2(0) remove = [0]*n for i in range(1,n): if dist[i]-minn[i]>a[i]: remove[i] = 1 # print (dist) # print (minn) # print (remove) print (n-g.bfs3(0)) ```
output
1
51,760
13
103,521
Provide tags and a correct Python 3 solution for this coding contest problem. Alyona decided to go on a diet and went to the forest to get some apples. There she unexpectedly found a magic rooted tree with root in the vertex 1, every vertex and every edge of which has a number written on. The girl noticed that some of the tree's vertices are sad, so she decided to play with them. Let's call vertex v sad if there is a vertex u in subtree of vertex v such that dist(v, u) > au, where au is the number written on vertex u, dist(v, u) is the sum of the numbers written on the edges on the path from v to u. Leaves of a tree are vertices connected to a single vertex by a single edge, but the root of a tree is a leaf if and only if the tree consists of a single vertex — root. Thus Alyona decided to remove some of tree leaves until there will be no any sad vertex left in the tree. What is the minimum number of leaves Alyona needs to remove? Input In the first line of the input integer n (1 ≤ n ≤ 105) is given — the number of vertices in the tree. In the second line the sequence of n integers a1, a2, ..., an (1 ≤ ai ≤ 109) is given, where ai is the number written on vertex i. The next n - 1 lines describe tree edges: ith of them consists of two integers pi and ci (1 ≤ pi ≤ n, - 109 ≤ ci ≤ 109), meaning that there is an edge connecting vertices i + 1 and pi with number ci written on it. Output Print the only integer — the minimum number of leaves Alyona needs to remove such that there will be no any sad vertex left in the tree. Example Input 9 88 22 83 14 95 91 98 53 11 3 24 7 -8 1 67 1 64 9 65 5 12 6 -80 3 8 Output 5 Note The following image represents possible process of removing leaves from the tree: <image>
instruction
0
51,761
13
103,522
Tags: dfs and similar, dp, graphs, trees Correct Solution: ``` n = int(input()) a = [int(x) for x in input().split()] g = [[] for _ in range(n)] for u in range(1, n): p, c = (int(x) for x in input().split()) g[p-1].append((u, c)) stack = [(0, 0, False)] r = 0 while stack: u, d, f = stack.pop() f = f or d > a[u] if f: r += 1 for v, c in g[u]: stack.append((v, d + c if d + c >= 0 else 0, f)) print(r) ```
output
1
51,761
13
103,523
Provide tags and a correct Python 3 solution for this coding contest problem. Alyona decided to go on a diet and went to the forest to get some apples. There she unexpectedly found a magic rooted tree with root in the vertex 1, every vertex and every edge of which has a number written on. The girl noticed that some of the tree's vertices are sad, so she decided to play with them. Let's call vertex v sad if there is a vertex u in subtree of vertex v such that dist(v, u) > au, where au is the number written on vertex u, dist(v, u) is the sum of the numbers written on the edges on the path from v to u. Leaves of a tree are vertices connected to a single vertex by a single edge, but the root of a tree is a leaf if and only if the tree consists of a single vertex — root. Thus Alyona decided to remove some of tree leaves until there will be no any sad vertex left in the tree. What is the minimum number of leaves Alyona needs to remove? Input In the first line of the input integer n (1 ≤ n ≤ 105) is given — the number of vertices in the tree. In the second line the sequence of n integers a1, a2, ..., an (1 ≤ ai ≤ 109) is given, where ai is the number written on vertex i. The next n - 1 lines describe tree edges: ith of them consists of two integers pi and ci (1 ≤ pi ≤ n, - 109 ≤ ci ≤ 109), meaning that there is an edge connecting vertices i + 1 and pi with number ci written on it. Output Print the only integer — the minimum number of leaves Alyona needs to remove such that there will be no any sad vertex left in the tree. Example Input 9 88 22 83 14 95 91 98 53 11 3 24 7 -8 1 67 1 64 9 65 5 12 6 -80 3 8 Output 5 Note The following image represents possible process of removing leaves from the tree: <image>
instruction
0
51,762
13
103,524
Tags: dfs and similar, dp, graphs, trees Correct Solution: ``` n = int(input()) a = [0] + list(map(int, input().split())) g = [list() for i in range(n+1)] for i in range(2, n+1): u, v = map(int, input().split()) g[i].append((u, v)) g[u].append((i, v)) vis = [0] * (n+1) stk = [(1, 0, 0)] while stk: v, min_d, dist = stk.pop() vis[v] = 1 for u, c in g[v]: if not vis[u]: if dist + c - min(min_d, dist+c) <= a[u]: stk.append((u, min(min_d, dist+c), dist+c)) print(n - vis.count(1)) ```
output
1
51,762
13
103,525
Provide tags and a correct Python 3 solution for this coding contest problem. Alyona decided to go on a diet and went to the forest to get some apples. There she unexpectedly found a magic rooted tree with root in the vertex 1, every vertex and every edge of which has a number written on. The girl noticed that some of the tree's vertices are sad, so she decided to play with them. Let's call vertex v sad if there is a vertex u in subtree of vertex v such that dist(v, u) > au, where au is the number written on vertex u, dist(v, u) is the sum of the numbers written on the edges on the path from v to u. Leaves of a tree are vertices connected to a single vertex by a single edge, but the root of a tree is a leaf if and only if the tree consists of a single vertex — root. Thus Alyona decided to remove some of tree leaves until there will be no any sad vertex left in the tree. What is the minimum number of leaves Alyona needs to remove? Input In the first line of the input integer n (1 ≤ n ≤ 105) is given — the number of vertices in the tree. In the second line the sequence of n integers a1, a2, ..., an (1 ≤ ai ≤ 109) is given, where ai is the number written on vertex i. The next n - 1 lines describe tree edges: ith of them consists of two integers pi and ci (1 ≤ pi ≤ n, - 109 ≤ ci ≤ 109), meaning that there is an edge connecting vertices i + 1 and pi with number ci written on it. Output Print the only integer — the minimum number of leaves Alyona needs to remove such that there will be no any sad vertex left in the tree. Example Input 9 88 22 83 14 95 91 98 53 11 3 24 7 -8 1 67 1 64 9 65 5 12 6 -80 3 8 Output 5 Note The following image represents possible process of removing leaves from the tree: <image>
instruction
0
51,763
13
103,526
Tags: dfs and similar, dp, graphs, trees Correct Solution: ``` nn=int(input()) a=[0]+list(map(int,input().split())) E=[[] for _ in range(nn+1)] for i in range(nn-1): p,c=map(int,input().split()) E[i+2]+=[(p,c)] E[p]+=[(i+2,c)] ans=0 ch=[(1,0,0)] while ch: nom,pre,l=ch.pop() if l>a[nom]: continue ans+=1 for x,c in E[nom]: if x!=pre: ch+=[(x,nom,max(l+c,c))] print(nn-ans) # Made By Mostafa_Khaled ```
output
1
51,763
13
103,527
Provide tags and a correct Python 3 solution for this coding contest problem. Alyona decided to go on a diet and went to the forest to get some apples. There she unexpectedly found a magic rooted tree with root in the vertex 1, every vertex and every edge of which has a number written on. The girl noticed that some of the tree's vertices are sad, so she decided to play with them. Let's call vertex v sad if there is a vertex u in subtree of vertex v such that dist(v, u) > au, where au is the number written on vertex u, dist(v, u) is the sum of the numbers written on the edges on the path from v to u. Leaves of a tree are vertices connected to a single vertex by a single edge, but the root of a tree is a leaf if and only if the tree consists of a single vertex — root. Thus Alyona decided to remove some of tree leaves until there will be no any sad vertex left in the tree. What is the minimum number of leaves Alyona needs to remove? Input In the first line of the input integer n (1 ≤ n ≤ 105) is given — the number of vertices in the tree. In the second line the sequence of n integers a1, a2, ..., an (1 ≤ ai ≤ 109) is given, where ai is the number written on vertex i. The next n - 1 lines describe tree edges: ith of them consists of two integers pi and ci (1 ≤ pi ≤ n, - 109 ≤ ci ≤ 109), meaning that there is an edge connecting vertices i + 1 and pi with number ci written on it. Output Print the only integer — the minimum number of leaves Alyona needs to remove such that there will be no any sad vertex left in the tree. Example Input 9 88 22 83 14 95 91 98 53 11 3 24 7 -8 1 67 1 64 9 65 5 12 6 -80 3 8 Output 5 Note The following image represents possible process of removing leaves from the tree: <image>
instruction
0
51,764
13
103,528
Tags: dfs and similar, dp, graphs, trees Correct Solution: ``` n=int(input()) a=[0]+list(map(int,input().split())) E=[[] for _ in range(n+1)] for i in range(n-1): p,c=map(int,input().split()) E[i+2]+=[(p,c)] E[p]+=[(i+2,c)] ans=0 ch=[(1,0,0)] while ch: nom,pre,l=ch.pop() if l>a[nom]: continue ans+=1 for x,c in E[nom]: t=l+c if l>0 else c if x!=pre: ch+=[(x,nom,t)] print(n-ans) ```
output
1
51,764
13
103,529
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Alyona decided to go on a diet and went to the forest to get some apples. There she unexpectedly found a magic rooted tree with root in the vertex 1, every vertex and every edge of which has a number written on. The girl noticed that some of the tree's vertices are sad, so she decided to play with them. Let's call vertex v sad if there is a vertex u in subtree of vertex v such that dist(v, u) > au, where au is the number written on vertex u, dist(v, u) is the sum of the numbers written on the edges on the path from v to u. Leaves of a tree are vertices connected to a single vertex by a single edge, but the root of a tree is a leaf if and only if the tree consists of a single vertex — root. Thus Alyona decided to remove some of tree leaves until there will be no any sad vertex left in the tree. What is the minimum number of leaves Alyona needs to remove? Input In the first line of the input integer n (1 ≤ n ≤ 105) is given — the number of vertices in the tree. In the second line the sequence of n integers a1, a2, ..., an (1 ≤ ai ≤ 109) is given, where ai is the number written on vertex i. The next n - 1 lines describe tree edges: ith of them consists of two integers pi and ci (1 ≤ pi ≤ n, - 109 ≤ ci ≤ 109), meaning that there is an edge connecting vertices i + 1 and pi with number ci written on it. Output Print the only integer — the minimum number of leaves Alyona needs to remove such that there will be no any sad vertex left in the tree. Example Input 9 88 22 83 14 95 91 98 53 11 3 24 7 -8 1 67 1 64 9 65 5 12 6 -80 3 8 Output 5 Note The following image represents possible process of removing leaves from the tree: <image> Submitted Solution: ``` """ Author : Arif Ahmad Date : 18-06-16 Algo : DFS Difficulty : Medium """ def main(): n = int(input()) a = list(map(int, input().split())) a.insert(0, 0) g = [[] for x in range(n+1)] cost = {} for i in range(2, n+1): p, c = map(int, input().split()) g[p].append((i, c)) stack = [(1, 0, False)] ans = 0 while stack: u, dist, sad = stack.pop() sad = sad or dist > a[u] if sad: ans += 1 for v, c in g[u]: stack.append((v, max(0, dist+c), sad)) print(ans) if __name__ == '__main__': main() ```
instruction
0
51,765
13
103,530
Yes
output
1
51,765
13
103,531
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Alyona decided to go on a diet and went to the forest to get some apples. There she unexpectedly found a magic rooted tree with root in the vertex 1, every vertex and every edge of which has a number written on. The girl noticed that some of the tree's vertices are sad, so she decided to play with them. Let's call vertex v sad if there is a vertex u in subtree of vertex v such that dist(v, u) > au, where au is the number written on vertex u, dist(v, u) is the sum of the numbers written on the edges on the path from v to u. Leaves of a tree are vertices connected to a single vertex by a single edge, but the root of a tree is a leaf if and only if the tree consists of a single vertex — root. Thus Alyona decided to remove some of tree leaves until there will be no any sad vertex left in the tree. What is the minimum number of leaves Alyona needs to remove? Input In the first line of the input integer n (1 ≤ n ≤ 105) is given — the number of vertices in the tree. In the second line the sequence of n integers a1, a2, ..., an (1 ≤ ai ≤ 109) is given, where ai is the number written on vertex i. The next n - 1 lines describe tree edges: ith of them consists of two integers pi and ci (1 ≤ pi ≤ n, - 109 ≤ ci ≤ 109), meaning that there is an edge connecting vertices i + 1 and pi with number ci written on it. Output Print the only integer — the minimum number of leaves Alyona needs to remove such that there will be no any sad vertex left in the tree. Example Input 9 88 22 83 14 95 91 98 53 11 3 24 7 -8 1 67 1 64 9 65 5 12 6 -80 3 8 Output 5 Note The following image represents possible process of removing leaves from the tree: <image> Submitted Solution: ``` def subtree_count(): stack = [0] while len(stack): v = stack[-1] size = 1 for u, _ in edge[v]: if u in subtree: size += subtree[u] else: stack.append(u) if stack[-1] is v: stack.pop() subtree[v] = size def remove_bfs(): queue = [(0, 0)] removed = 0 while len(queue): v, s = queue.pop() if s > vertex[v]: removed += subtree[v] else: for u, c in edge[v]: queue.append((u, max(s + c, 0))) return removed n = int(input()) vertex = list(map(int, input().split())) edge = {} subtree = {} for i in range(n): edge[i] = [] for i in range(n - 1): p, c = map(int, input().split()) edge[p - 1].append((i + 1, c)) subtree_count() print(remove_bfs()) ```
instruction
0
51,766
13
103,532
Yes
output
1
51,766
13
103,533
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Alyona decided to go on a diet and went to the forest to get some apples. There she unexpectedly found a magic rooted tree with root in the vertex 1, every vertex and every edge of which has a number written on. The girl noticed that some of the tree's vertices are sad, so she decided to play with them. Let's call vertex v sad if there is a vertex u in subtree of vertex v such that dist(v, u) > au, where au is the number written on vertex u, dist(v, u) is the sum of the numbers written on the edges on the path from v to u. Leaves of a tree are vertices connected to a single vertex by a single edge, but the root of a tree is a leaf if and only if the tree consists of a single vertex — root. Thus Alyona decided to remove some of tree leaves until there will be no any sad vertex left in the tree. What is the minimum number of leaves Alyona needs to remove? Input In the first line of the input integer n (1 ≤ n ≤ 105) is given — the number of vertices in the tree. In the second line the sequence of n integers a1, a2, ..., an (1 ≤ ai ≤ 109) is given, where ai is the number written on vertex i. The next n - 1 lines describe tree edges: ith of them consists of two integers pi and ci (1 ≤ pi ≤ n, - 109 ≤ ci ≤ 109), meaning that there is an edge connecting vertices i + 1 and pi with number ci written on it. Output Print the only integer — the minimum number of leaves Alyona needs to remove such that there will be no any sad vertex left in the tree. Example Input 9 88 22 83 14 95 91 98 53 11 3 24 7 -8 1 67 1 64 9 65 5 12 6 -80 3 8 Output 5 Note The following image represents possible process of removing leaves from the tree: <image> Submitted Solution: ``` nn=int(input()) a=[0]+list(map(int,input().split())) E=[[] for _ in range(nn+1)] for i in range(nn-1): p,c=map(int,input().split()) E[i+2]+=[(p,c)] E[p]+=[(i+2,c)] ans=0 ch=[(1,0,0)] while ch: nom,pre,l=ch.pop() if l>a[nom]: continue ans+=1 for x,c in E[nom]: if x!=pre: ch+=[(x,nom,max(l+c,c))] print(nn-ans) ```
instruction
0
51,767
13
103,534
Yes
output
1
51,767
13
103,535
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Alyona decided to go on a diet and went to the forest to get some apples. There she unexpectedly found a magic rooted tree with root in the vertex 1, every vertex and every edge of which has a number written on. The girl noticed that some of the tree's vertices are sad, so she decided to play with them. Let's call vertex v sad if there is a vertex u in subtree of vertex v such that dist(v, u) > au, where au is the number written on vertex u, dist(v, u) is the sum of the numbers written on the edges on the path from v to u. Leaves of a tree are vertices connected to a single vertex by a single edge, but the root of a tree is a leaf if and only if the tree consists of a single vertex — root. Thus Alyona decided to remove some of tree leaves until there will be no any sad vertex left in the tree. What is the minimum number of leaves Alyona needs to remove? Input In the first line of the input integer n (1 ≤ n ≤ 105) is given — the number of vertices in the tree. In the second line the sequence of n integers a1, a2, ..., an (1 ≤ ai ≤ 109) is given, where ai is the number written on vertex i. The next n - 1 lines describe tree edges: ith of them consists of two integers pi and ci (1 ≤ pi ≤ n, - 109 ≤ ci ≤ 109), meaning that there is an edge connecting vertices i + 1 and pi with number ci written on it. Output Print the only integer — the minimum number of leaves Alyona needs to remove such that there will be no any sad vertex left in the tree. Example Input 9 88 22 83 14 95 91 98 53 11 3 24 7 -8 1 67 1 64 9 65 5 12 6 -80 3 8 Output 5 Note The following image represents possible process of removing leaves from the tree: <image> Submitted Solution: ``` n = int(input()) A = list(map(int, input().split())) maxDist = [0] * n G = [[] for _ in range(n)] for v in range(1, n): u, d = tuple(map(int, input().split())) u -= 1 G[v].append((u, d)) G[u].append((v, d)) seen = [False] * n seen[0] = True q = [0] to_remove = [] while q: v = q.pop(); for u, dist in G[v]: if not seen[u]: seen[u] = True maxDist[u] = max(dist, maxDist[v] + dist) if maxDist[u] > A[u]: to_remove.append(u) else: q.append(u) count = 0 while to_remove: v = to_remove.pop() count += 1 for u, _ in G[v]: if not seen[u]: seen[u] = True to_remove.append(u) print(count) ```
instruction
0
51,768
13
103,536
Yes
output
1
51,768
13
103,537
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Alyona decided to go on a diet and went to the forest to get some apples. There she unexpectedly found a magic rooted tree with root in the vertex 1, every vertex and every edge of which has a number written on. The girl noticed that some of the tree's vertices are sad, so she decided to play with them. Let's call vertex v sad if there is a vertex u in subtree of vertex v such that dist(v, u) > au, where au is the number written on vertex u, dist(v, u) is the sum of the numbers written on the edges on the path from v to u. Leaves of a tree are vertices connected to a single vertex by a single edge, but the root of a tree is a leaf if and only if the tree consists of a single vertex — root. Thus Alyona decided to remove some of tree leaves until there will be no any sad vertex left in the tree. What is the minimum number of leaves Alyona needs to remove? Input In the first line of the input integer n (1 ≤ n ≤ 105) is given — the number of vertices in the tree. In the second line the sequence of n integers a1, a2, ..., an (1 ≤ ai ≤ 109) is given, where ai is the number written on vertex i. The next n - 1 lines describe tree edges: ith of them consists of two integers pi and ci (1 ≤ pi ≤ n, - 109 ≤ ci ≤ 109), meaning that there is an edge connecting vertices i + 1 and pi with number ci written on it. Output Print the only integer — the minimum number of leaves Alyona needs to remove such that there will be no any sad vertex left in the tree. Example Input 9 88 22 83 14 95 91 98 53 11 3 24 7 -8 1 67 1 64 9 65 5 12 6 -80 3 8 Output 5 Note The following image represents possible process of removing leaves from the tree: <image> Submitted Solution: ``` n = int(input()) vertices = list(map(int, input().split())) edges = {} for i in range(n-1): e, w = list(map(int, input().split())) if e not in edges: edges[e] = [] edges[e].append([i+2, w]) def count_sad_leaves(n, w): removes = 0 if n in edges: for e in edges[n]: removes += count_sad_leaves(e[0], max(w + e[1], e[1])) if vertices[n-1] < w: removes += 1 return removes print(count_sad_leaves(1, 0)) ```
instruction
0
51,769
13
103,538
No
output
1
51,769
13
103,539