Tourism business
Time limit5sMemory limit1024 MB
Given a weighted tree and two city sets A and B with populations, find the maximum of (C_X + C_Y) times the path distance over all X in A and Y in B.
- Level
Hard8 of 10
- Topics
- Tree, Divide and conquer, Dynamic programming
- Solved
- No attempts yet
Problem
Octorabbit Kingdom has cities connected by roads. From any city, you can reach any other city using only roads, so the country forms a tree. Each road has a positive integer length. The distance between two cities is the sum of the road lengths on the simple path that connects them.
For a new tourism project, the country picks two cities and and makes them tourism sister cities. Once paired, people from each city travel to visit the other. Let be the distance between and , and let and be the populations living in and . The transport fee income is .
The country is going through upheaval, so city populations keep changing, and the cities that want to join vary from situation to situation. The country needs to find the right pairs for many different situations.
There are sister city plans. Each plan gives a set of candidate cities for and a set of candidate cities for , along with the population of each candidate city. No city is in both and .
For each plan, find the maximum transport fee income that can be obtained by choosing and .
Input
The first line contains and , separated by a space. (, )
The next lines each contain , , and , separated by spaces. The -th road connects city and city , and has length . (, )
Then the plans follow in this format.
- The first line contains and , separated by a space. is the size of , and is the size of . ()
- The next lines each contain and , separated by a space. City belongs to set and has a population of , that is, . (, )
- The next lines each contain and , separated by a space. City belongs to set and has a population of , that is, . (, )
The sum is at most .
Output
Print the maximum transport fee income for each sister city plan on its own line, in order.
Hint

When and , the transport fee income is , which is optimal. and is also optimal.