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/python3importmathimportosimportrandomimportreimportsysfromcollectionsimportdefaultdictdef_compute_edges_and_n_nodes(visit_node:int,children:dict,visited:set)->(int,int):"""Returnshowmanyedgescanremovethissubtreeandhowmanynodesitcontains"""# As children dict is bidirectional, we have to add nodes to visit in order to# avoid eternal loopvisited.add(visit_node)# Exit case: Node is leaf, so it can not be a forest for its ownifnotlen(children[visit_node]):return(0,1)# We start counting nodes at 1 as we are assuming current nodeedges_to_remove,n_nodes=0,1forchildinchildren[visit_node]:ifchildinvisited:continuechild_edges_to_remove,child_n_nodes=_compute_edges_and_n_nodes(child,children,visited)edges_to_remove+=child_edges_to_removen_nodes+=child_n_nodes# If subtree is even, we add 1 edge to removeifnotn_nodes%2:edges_to_remove+=1returnedges_to_remove,n_nodes# Complete the evenForest function below.defevenForest(t_nodes,t_edges,t_from,t_to):chldren=defaultdict(list)forn_from,n_toinzip(t_from,t_to):chldren[n_from].append(n_to)chldren[n_to].append(n_from)# We substract 1 to number of edges to remove because we don't want to count rootreturn_compute_edges_and_n_nodes(1,chldren,set())[0]-1if__name__=='__main__':fptr=open(os.environ['OUTPUT_PATH'],'w')t_nodes,t_edges=map(int,input().rstrip().split())t_from=[0]*t_edgest_to=[0]*t_edgesforiinrange(t_edges):t_from[i],t_to[i]=map(int,input().rstrip().split())res=evenForest(t_nodes,t_edges,t_from,t_to)fptr.write(str(res)+'\n')fptr.close()
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
An unexpected error occurred. Please try reloading the page. If problem persists, please contact support@hackerrank.com
Even Tree
You are viewing a single comment's thread. Return to all comments →
PYTHON SIMPLE DFS SOLUTION