Ninja Delivery
Time limit1sMemory limit1024 MB
Pick hubs x and y on a tree to minimize the total weighted cost of Q requests, where each request goes from a to x, x to y, then y to b.
- Level
Hard8 of 10
- Topics
- Tree, Divide and conquer, Dynamic programming, DFS
- Solved
- No attempts yet
Problem
Byeongwoo is the village head of Leaf village. Leaf village has markets and bidirectional roads of length that connect pairs of markets. Any two different markets can reach each other using only roads. In other words, Leaf village is shaped like a tree. For convenience, the markets are numbered from to .
Recently, the economy of Leaf village has grown, so goods need to be moved between markets more often. There are such requests. Each request is written as three integers , meaning that kg of goods must be moved from market to market . Byeongwoo hired ninjas to handle the requests. To use the ninja parcel service efficiently, he must choose two markets and to serve as logistics hubs. and do not need to be different.
For two markets and , let be the shortest distance from to when traveling only along roads.
- All goods must first be gathered at market . Moving goods from market to market costs per kilogram per unit distance.
- Then the ninjas use a mysterious technique to move all goods at market to market . This costs per kilogram per unit distance.
- Finally, goods are carried from market to the destination of each request. Moving goods to market costs per kilogram per unit distance.
In other words, moving kg of goods from market to market costs . Choose the markets and so that the total cost of all requests is minimized, and write a program that finds this minimum.
Input
The first line contains the number of markets .
Each of the next lines contains two integers and , separated by a space. This means that the -th road connects market and market . It is guaranteed that and that the roads form a tree.
Each of the next lines contains two integers and , separated by a space. is the cost per unit distance per kilogram of moving goods from market to market . is the cost per unit distance per kilogram of moving goods from market to market .
The line after that contains the number of requests .
Each of the next lines contains three integers , , and , separated by spaces. This means that kg of goods must be moved from market to market . and may be equal, and the same pair may appear in more than one request.
The last line contains , the cost per unit distance per kilogram of moving goods from market to market .
Output
Print the minimum possible total cost of all requests on the first line.
Constraints
- For all requests , .