Energy
Time limit1sMemory limit1024 MB
Choose exactly k vertex-disjoint paths in a tree to maximize the total energy of the rooms they cover.
- Level
Medium7 of 10
- Topics
- Dynamic programming, Tree, DFS
- Solved
- No attempts yet
Problem
Villain Van Pelt needs to charge his game console urgently. For this, he uses an underground maze with energy sources.
The maze has rooms numbered from 1 to . Some pairs of rooms are connected by corridors, which can be traveled in both directions.
A path between rooms and is a sequence of rooms where , , and for every , rooms and are connected by a corridor. Any two rooms have exactly one path between them, so the maze is a tree with exactly corridors.
Van Pelt does not want to enter the dark, frightening maze himself. Instead, he sends jaguars to fetch energy. For each jaguar, Van Pelt chooses a pair of rooms (possibly the same room), and the jaguar walks through every room on the path between them, including the chosen rooms. The jaguars are aggressive, so no two chosen paths may share a room, or the jaguars may fight. Van Pelt must send every jaguar.
Each room has an energy source holding units of energy in room . A source may hold negative energy. Each jaguar takes the energy from every source on its path. The energy Van Pelt receives is the total energy taken by the jaguars.
Find the maximum amount of energy Van Pelt can receive.
Input
The first line contains two integers and (, ), the number of rooms and the number of jaguars.
The second line contains integers (), separated by spaces.
Each of the next lines contains two integers and , the rooms connected by a corridor.
Output
Print a single integer, the maximum amount of energy Van Pelt can receive.
Hint
In the sample from the statement, Van Pelt can send one jaguar on the path between rooms 3 and 7 and another on the path between rooms 5 and 6. The jaguars then cover rooms 3, 7, 5, 4, and 6, collecting 14 units of energy.