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.
defjeanisRoute(n,cities,roads):"""The strategy of this approach is to:1)Pruneoffanybranchesofthetreethataren'tvisited2)Notethattovisiteachremainingnodeandreturntostarthaslength=2*sum(allremainingedgeweights)3)Sinceweneednotreturntostart,themostbywhichwecanreducetotallengthisthemaxdistanceb/w2nodesi.e.thetree'sdiameter."""# Make the adjacency list and sum (2x) total graph weightadj={i:[]foriinrange(1,n+1)}total=0foru,v,winroads:adj[u].append((v,w))adj[v].append((u,w))total+=2*w# Iteratively, prune leaves that are not visited (adjusting total)flag=True#trackifanychangesmadethispassnon_dest=set(range(1,n+1)).difference({*cities})whileflag:flag=Falseforuinnon_dest:iflen(adj[u])==1:v,w=adj[u].pop()adj[v].remove((u,w))flag=Truetotal-=2*w# Compute the pruned tree's diameter by running DFS twice.# First time, start at any city and find the furthest leaf.# Second time, start at first endpoint. Result is the diameteru,d=dfs(cities[0],adj)v,diameter=dfs(u,adj)returntotal-diameterdefdfs(start,adj):"Conduct DFS to find the node of max distance from node <start>"seen=set([start])queue=[(start,0)]end,max_dist=start,0whilequeue:curr,dist=queue.pop()fornxt,wtinadj[curr]:ifnxtnotinseen:seen.add(nxt)new_dist=dist+wtqueue.append((nxt,new_dist))ifnew_dist>max_dist:end,max_dist=nxt,new_distreturnend,max_dist
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Jeanie's Route
You are viewing a single comment's thread. Return to all comments →
python3