Byteland has N cities (numbered from to ) and N-1 bidirectional roads. It is guaranteed that there is a route from any city to any other city.
Jeanie is a postal worker who must deliver Kletters to various cities in Byteland. She can start and end her delivery route in any city. Given the destination cities for K letters and the definition of each road in Byteland, find and print the minimum distance Jeanie must travel to deliver all K letters.
Note: The letters can be delivered in any order.
The first line contains two space-separated integers, N (the number of cities) and K (the number of letters), respectively. The second line contains K space-separated integers describing the delivery city for each letter. Each line i of the N-1 subsequent lines contains 3 space-separated integers describing a road as ui,vi,di , where di is the distance (length) of the bidirectional road between cities ui and vi.
sample:
5 3
1 3 4
1 2 1
2 3 2
2 4 2
3 5 3
output:
6
path:3-2-1-2-4
approach for this problem
What is V here?? O(V+E) Also are the edges weighted or assumed weight = 1
linear solution indended V->vertices yes weighted
Auto comment: topic has been updated by _Aryan_ (previous revision, new revision, compare).
Auto comment: topic has been updated by _Aryan_ (previous revision, new revision, compare).
UPD: https://www.hackerrank.com/challenges/jeanies-route/problem Same Problem
First, notice that you only care about the deepest nodes because you when you visit a node you will always visit its children next (else you're doing some suboptimal path). Also notice we won't go down a subtree that has no delivery node. Thus the problem is reduced to visiting the K leaves. It is easy to solve if the weights are all one so you can generalise this approach
how will you find diameter its weighted?
Diameter of weighted tree can be calculated using the same algorithm as for unweighted tree
thanks done
https://pastebin.com/VzTRpdtF My accepted Code by approach I told!!
nice approach....nice implementation part(that queue one thing was awesome)
The following approach only works if the distance between any two cities is non-negative.
A possibility is to get the minimum distance of passing through all of them and then returning to the start(starting on one of the $$$K$$$ cities) then subtract the maximum distance between two special nodes. Both calculations can be done with a relatively simple dfs/bfs. This has the significance of starting from one of the nodes and running to all of them and stopping at the other special node.
I got the final solution done, but just wondering if this is solvable by finding minimum spanning tree and centroid then find all k nodes' distance from centroid?
How do you find the minimum spanning tree of a tree?
ok nvm i didnt see notice its a tree itself