Secret Base
Time limit7sMemory limit1024 MB
Given a weighted tree where point weights change, after each update find the minimum total weighted distance from all people to a single city.
- Level
Medium7 of 10
- Topics
- Tree, Segment tree, Binary search
- Solved
- No attempts yet
Statement
설곽국 is a country with N cities numbered from 1 to . There are roads connecting pairs of cities, and all cities are connected. Every road has length .
One day, the neighboring country 경곽국 announced an invasion through a news report. The nervous people of 설곽국 decided to build a secret base. The base is built temporarily and simply, so it can be moved easily.
The base is built in a city that satisfies the following property.
- If the base is built in city , define as the sum of the travel distances of all people to city . Here is the distance between city and city .
- The base is built in a city where is minimal among all cities. If several cities qualify, the base can be built in any of them.
Brue, who lives in 설곽국, wants to know the total travel distance of the people after building the base.
Over time, the number of people in a city changes exactly times. After each change, the total travel distance may change, and the base may move as a result. Find the total travel distance for every time point.
Input
The first line contains the number of cities and the number of changes .
The second line contains the number of people in each city , , , , separated by spaces.
From the third line, the next lines describe the road structure of 설곽국. The -th line contains two integers and , meaning that road connects city and city .
From line , the next lines describe the changes as . This means the number of people in city becomes .
Output
Print lines. The first line is the total travel distance to the base in the initial state, and each of the next lines is the total travel distance after each population change.
Constraints
- ()
- The input is guaranteed to be a valid tree.
- ()
- ()
Hint
The distance between two cities and is the number of roads on the shortest path from city to city .