We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
- Prepare
- Algorithms
- Search
- Cut the Tree
- Discussions
Cut the Tree
Cut the Tree
Sort by
recency
|
167 Discussions
|
Please Login in order to post a comment
!/bin/python3
simpelst one and solvable one i tried
import math import os import random import re import sys sys.setrecursionlimit(10**6)
def cutTheTree(data, edges): n = len(data) # adjacency (1-based nodes): convert to 0-based indices adj = [[] for _ in range(n)] for u, v in edges: u -= 1; v -= 1 adj[u].append(v) adj[v].append(u)
if name == 'main': fptr = open(os.environ['OUTPUT_PATH'], 'w')
We can make a mapping of each node, to the sum of their tree. In this case, the root node has a sum equal to the entire tree, and each other node the respective cost of their subtree.
If we cut at an edge, we spawn two subtrees: one where we just cut (with a sum equal to the mapping of that node) and a 'bigger' tree, with sum equal to the entire tree (i.e., mapping[1]) - the tree we just removed. With this idea, we can map each node to the sum of its tree in O(V + E), and then cut every edge once, perfoming the check in O(1), giving a further O(V + E).
The total time complexity then becomes O(V + E), with O(V + E) space, too.