Dividing the Gems
Time limit1sMemory limit128 MB
Simulate an alternating gem-picking game where one player greedily picks by fixed rules while the other plays optimally to maximize his own total, tie-breaking for the opponent's total, and output final scores.
- Level
Hard8 of 10
- Topics
- Greedy, Game theory, Sorting
- Solved
- No attempts yet
Problem
Petra and Jan want to share a box full of gems. Dividing it fairly is hard, because the two of them value each gem differently.
They take turns removing gems, one gem per turn, and repeat this until no gems remain. A coin flip decides who takes the first turn.
Petra and Jan follow different strategies.
- On her turn, Petra takes the remaining gem she values the most. If several gems are tied for her highest value, she takes the one among them that Jan values the least.
- Jan takes gems so that the total value he ends up with is as large as possible. If several choices achieve that maximum, he takes gems so that the total value Petra ends up with is also as large as possible.
Given who starts and how each person values every gem, compute the total gem value that each person finally collects.
Input
The first line contains the number of test cases (). Each test case is given as follows.
- The first line contains the number of gems ().
- The second line contains the name of the person who takes the first turn:
Petraif Petra starts, orJanif Jan starts. - Each of the next lines contains two integers, Petra's value and Jan's value for one gem ().
Output
For each test case, print one line containing the total value Petra finally collects and the total value Jan finally collects, in that order, separated by a space.