Empty Stalls
Time limit1sMemory limit128 MB
Cows each take the next free stall clockwise from their wish on a ring of N stalls, and the task asks for the smallest stall number left empty.
- Level
Medium6 of 10
- Topics
- Union-find, Simulation
- Solved
- No attempts yet
Problem
Farmer John's new barn is a ring of stalls () numbered through , and stall sits next to stall .
At the end of each day the cows come back to the barn one at a time, and every cow has one stall she wants. If that stall is already taken, she looks at the stalls in increasing order of number, starting from the one she wants, and claims the first empty stall she meets. Once she passes stall she keeps looking from stall .
Given the preferred stall of every cow, find the smallest number among the stalls that are still empty after all the cows are back. The answer does not depend on the order in which the cows return.
To keep the input from growing too large, the preferred stalls are given in compressed form on lines (). Each line has the form X Y A B.
One such line describes the stalls wanted by cows. With , there are cows that want each of the stalls . Both and are between and .
Input
- Line 1: two space-separated integers and .
- Lines 2 through : each line contains the integers , , , described above. Together these lines describe at most cows. Several lines may add cows to the same stall.
Output
- Line 1: print the smallest number of a stall that stays empty.
Hint
The barn in the sample has 10 stalls numbered through . The line 3 2 2 4 means 3 cows want stall and 3 cows want stall . The line 2 1 0 1 means 2 cows want stall , and the line 1 1 1 7 means 1 cow wants stall , so 4 cows want stall 8 in total. All 9 cows fit, and stall 5 is the only one left empty.