Artifacts
Time limit1.5sMemory limit1024 MB
Find the minimum walk on a weighted tree that visits sites holding all k artifact kinds, where the start and end points cost nothing.
- Level
Hard8 of 10
- Topics
- Tree, Dynamic programming, Bit manipulation, DFS
- Solved
- No attempts yet
Statement
Rick and Morty found a map of a planet in another dimension. The map shows dig sites connected by paths. Path connects sites and and has length . There are exactly paths, and every site can reach every other site, so the structure is a tree. An alien informant reported that there are kinds of artifacts in total, and site holds an artifact of kind . Rick is in a competition with a known tomb raider and must collect all kinds. Advanced technology does not work in this dimension. Rick can create portals at the start and end points of the route in advance, but he must walk the rest of the route. He chooses the start point, the end point, and the route (not necessarily simple) so that the distance he walks is minimal, and the route collects all kinds of artifacts.
Input
The first line contains two integers and (; ), separated by a space. They are the number of sites and the number of required artifact kinds. The next line contains integers (), the artifact kind at each site. If , site holds no artifact. The next lines each contain three integers , , (; ). This means a path of length connects sites and . The input graph is guaranteed to be a tree.
Output
If it is impossible to collect all kinds of artifacts, print . Otherwise, print the minimum distance Rick must walk to collect all kinds of artifacts.
Hints
In the first example, one optimal route is . In the second example, no site holds artifact kind 5, so it is impossible to collect all five kinds. In the third example, one optimal route is .