The Best Teams
Time limit2sMemory limit128 MB
Given N players each with an age and distinct skill, and forbidden pairs that are adjacent in skill order, answer T queries each asking the maximum sum of at most K players with age at most A.
- Level
Hard8 of 10
- Topics
- Dynamic programming, Sorting, Greedy, Binary search
- Solved
- No attempts yet
Problem
For each of several tournaments, a selector must pick the strongest possible team. There are players available, and each player has an age and a skill. The strength of a team equals the sum of the skills of its players.
However, two players with similar skills must never be placed on the same team, because they would interfere with each other and fail to collaborate. Two players are said to have similar skills if no other player has a skill value strictly between theirs. Since all skill values are distinct, this is exactly the condition that the two players are adjacent in the list of all players sorted by skill.
Teams are chosen for tournaments. Each tournament has two restrictions:
- an age limit : every chosen player must have age at most ;
- a size limit : the team may contain at most players.
Tournaments are independent, so a player may be used in more than one tournament. Note that the adjacency (the similar skills relation) is always defined over the full sorted list of all players, regardless of which players are eligible for a given tournament.
For each tournament, determine the strength (total skill) of the strongest valid team the selector can assemble.
Input
The first line contains an integer — the number of players.
Each of the next lines contains two space-separated integers and — the age and skill of the -th player.
The next line contains an integer — the number of tournaments.
Each of the next lines contains two integers and — the age limit and the team-size limit of the -th tournament.
Output
For each tournament, print a single integer on its own line: the strength (total skill) of the strongest valid team, in the same order as the tournaments are given.
If no player can be selected, print 0. Use a 64-bit integer type, since the answer can be large.
Constraints
- All skill values are distinct.
Explanation
In the sample, sorting the players by skill gives the order (by input index) . Hence the pairs of players with similar skills — those that cannot share a team — are .
- Tournament 1 (, ): the best team is players with total skill .
- Tournament 2 (, ): the best team is players with total skill .
- Tournament 3 (, ): the best team is players with total skill .
- Tournament 4 (, ): every player is older than , so no team can be formed and the answer is .