Frozen Sprinklers
InterviewTime limit3sMemory limit128 MB
Cut pipes with minimum total force so no water flows from the central node to any leaf sprinkler in the tree.
- Level
Medium5 of 10
- Topics
- Dynamic programming, Tree, DFS
- Solved
- No attempts yet
Problem
This winter is said to be the coldest in a hundred years. The city of Haebin wants to protect its park before the cold sets in, and the first job is draining the water left in the sprinklers.
Water drawn from the well enters the central node and runs along the pipes to neighboring nodes. Every node is either a sprinkler or an internal node that splits the water.
- Except for the central node, which sits directly on the well, every node has exactly one pipe supplying it with water.
- Every internal node has at least one pipe carrying water on to another node. A sprinkler has no outgoing pipe.
- Every pipe carries a valve, and shutting a valve stops the water in that pipe. The force needed to shut a valve differs from pipe to pipe.
Shin Haebin, a city official, knows the sprinkler plumbing by heart and knows how much force each valve takes.
Haebin is lazy. He wants to shut a few valves and leave every sprinkler dry, spending as little force as he can.
How much force does he need?
Input
The input holds several test cases and continues to the end of the file.
The first line of each test case has the number of nodes () and the number of the central node ().
Each of the next lines describes one pipe with three integers , () and (). A pipe joins node and node , and shutting its valve takes force .
The pipes form a tree that connects all nodes.
Output
For each test case print, on its own line, the smallest total force needed to shut valves so that no water reaches any sprinkler.