Japanese Lottery
Time limit4sMemory limit1024 MB
After each toggle of a horizontal bar in an Amida-kuji grid, find the fewest bars to remove so that every start leg reaches its matching prize.
- Level
Hard9 of 10
- Topics
- Dynamic programming, Segment tree, Bit manipulation
- Solved
- No attempts yet
Problem
Amida-kuji is a lottery popular in Japan that can be used to assign prizes to people. The game consists of vertical lines, called legs, and some horizontal bars that connect adjacent legs. The tops of the legs are the starting positions of the people, and the prizes are at the bottom of the legs. To find the prize of the th person, start at the top of the th leg, move down, and switch legs whenever a horizontal bar is encountered. Figure J.1 shows such a game and how to trace a path.

Figure J.1: A visualization of an Amida-kuji game. The first person is connected to the third prize. This is the game with all connections added and none removed. To connect the th person to the th prize, you must remove both horizontal bars between legs 2 and 3 and the topmost horizontal bar between legs 3 and 4. This is the only minimal solution.
The initial game has no horizontal bars. Then bars are added one by one or removed again. After each change, find the minimum number of horizontal bars that must be removed so that the th person gets the th prize for every . Removing all horizontal bars always works, so an answer always exists.
Input
The first line contains three integers , , and (, ), the number of legs, the height of the legs, and the number of changes.
Each of the next lines contains three integers , , and (, ). This describes a change where a horizontal bar at height between legs and is added or removed. If a bar already exists at that position, it is removed. Otherwise, it is added. The two legs are guaranteed to be adjacent, so .
At every moment, all horizontal bars have different heights.
Output
After each change, print one integer on its own line: the minimum number of horizontal bars that must be removed from the game with the bars that currently exist, so that the th person gets the th prize for every .