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.
#!/bin/python3importmathimportosimportrandomimportreimportsys## Complete the 'cutTheTree' function below.## The function is expected to return an INTEGER.# The function accepts following parameters:# 1. INTEGER_ARRAY data# 2. 2D_INTEGER_ARRAY edges#sys.setrecursionlimit(10**7)classVertex:def__init__(self,value):self.value=valueself.edges=[]self.is_init=Falsedefadd_edge(self,vertex):self.edges.append(vertex)definit(vertex,parent,sum_cache):vertex.is_init=Truesubtotal=vertex.valueforadjinvertex.edges:ifadjisnotparent:subtree_sum=init(adj,vertex,sum_cache)sum_cache[(vertex,adj)]=subtree_sumsum_cache[(adj,vertex)]=sum_cache_total-subtree_sumsubtotal+=subtree_sumreturnsubtotaldefmin_diff(vertices,sum_cache,total_sum):min_diff_value=total_sumforvinvertices:foradjinv.edges:diff=abs(total_sum-2*sum_cache[(v,adj)])ifdiff<min_diff_value:min_diff_value=diffreturnmin_diff_valueN=int(sys.stdin.readline())values=list(map(int,sys.stdin.readline().split()))vertices=[Vertex(val)forvalinvalues]for_inrange(N-1):a,b=map(int,sys.stdin.readline().split())vertices[a-1].add_edge(vertices[b-1])vertices[b-1].add_edge(vertices[a-1])sum_cache={}sum_cache_total=sum(values)init(vertices[0],None,sum_cache)result=min_diff(vertices,sum_cache,sum_cache_total)print(result)
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Cut the Tree
You are viewing a single comment's thread. Return to all comments →