Potion Farming
Time limit2sMemory limit1024 MB
Given a tree rooted at room 1 and a schedule of potion spawns, find the most potions collectible while covering every room with the fewest root-to-room paths.
Problem
You are playing your favorite mobile game and trying to farm potions so that you may have a chance at defeating the legendary cow boss. The game map is a series of rooms labeled , connected by edges that form a tree.
You can explore the map by making a series of "traversals". A traversal is a simple path from room to any other room in the tree. Once you finish one traversal, you can start another traversal from room . The map is complete once every room has been visited by at least one traversal. Your main goal is to complete the map in the minimum number of traversals.
Your secondary goal is to farm as many potions as possible. Before a traversal begins, a potion spawns at some room in the map. You can pick up the potion by visiting that room during the current traversal. If you do not pick up the potion, it disappears when the current traversal ends, so you cannot pick it up in later traversals.
You have studied the game files and know where the potions will appear before your next traversals. If you complete the map in the minimum number of traversals, what is the maximum number of potions you can farm from the map?
Input
The first line contains an integer , the number of rooms in the map.
The next line contains space-separated integers where , and is the room where a potion appears before the th traversal.
The last lines each contain two space-separated integers , an edge between rooms and . These edges form a tree.
Output
Output one line containing a single integer, the maximum number of potions you can farm from the map in the minimum number of traversals.