Santa Claus
Time limit1sMemory limit1024 MB
For each house i, find the minimum distance 2X_i - X_L Santa walks so that every elf gift can be handed to a child who accepts it.
- Level
Hard9 of 10
- Topics
- Greedy, Segment tree, Binary search
- Solved
- No attempts yet
Problem
On Christmas Eve, Santa takes gifts from the elves and gives them to children, bringing joy to their hearts.
The city has houses along a road, numbered from 1 to (). House has the following data:
- (): the position of house on the road
- ()
- ()
If , house has an elf holding one gift of value . If , house has a child waiting for one gift of minimum value .
There are scenarios. In scenario , Santa enters the city at coordinate 0 with an empty gift bag. He first walks right to house at coordinate , then walks left to some position . Each time he passes an elf's house he has not visited before, he takes that gift and puts it in the bag. Each time he passes a child's house that has not yet received a gift, he can (but does not have to) pick one gift from the bag and hand it to the child. The chosen gift must have a value at least as large as , the child's minimum, and it is removed from the bag.
In scenario , Santa travels the distance . For each scenario, find the minimum distance Santa must travel to give out all the elves' gifts. Some children may receive no gift, but all gifts must be distributed and no child may receive more than one. If no such exists, set . In particular, if Santa cannot reach all the elves' houses, the answer for that scenario is always .
Input
The first line contains one integer (), the number of tests. Each test consists of four lines:
- Line 1: the number of houses
- Line 2:
- Line 3:
- Line 4:
The sum of over all tests does not exceed 500 000.
Output
For each test, output a single line with integers .
Hint
In the first test of the first input, there are 8 houses. Houses 2, 3 and 4 each hold an elf with a gift of value 2, 3 and 3 respectively. House 5 holds a child who wants a gift of value 5. No elf has a gift that large, so that child receives nothing.
In scenarios 1, 2 and 3, Santa does not visit all the elves, so .
In scenarios 4, 5 and 6, Santa does not visit enough children who accept his 3 gifts, so .
In scenario 7, Santa must return to the first house () to give out all 3 gifts, so .
In scenario 8, Santa does not need to return at all () to give out all 3 gifts, so .