Buffalo Barricades
Time limit5sMemory limit512 MB
For each settler arriving in order, count the buffalos inside the region bounded by rivers and fences whose upper right corner is the settler's post.
- Level
Hard8 of 10
- Topics
- Sorting, Prefix sum, Stack, BFS
- Solved
- No attempts yet
Problem
A pasture in the wild west is a rectangular grid in the upper right quadrant of the coordinate plane. buffalos are scattered over the pasture, and each one occupies a single unit square. The buffalos are numbered through , and buffalo stands in the unit square whose upper right corner is the integer point . The two coordinate axes are rivers that meet at the origin, so no buffalo can leave to the left or downward.
settlers arrive one at a time, and each of them claims land this way.
- The settler picks an integer point and drives one fence post into it. The chosen point holds no earlier post, and no earlier fence runs through it. No two posts share an coordinate, and no two posts share a coordinate.
- Starting at the post, the settler builds a horizontal fence to the left and a vertical fence downward. Each fence runs as far as it can, until it reaches a river or a fence that is already standing.
- The settler takes the whole connected area bounded by fences and rivers whose upper right corner is his post, together with every buffalo inside it. A settler who arrives later may take land that an earlier settler already claimed.
For each settler, find how many buffalos he claimed at the moment he arrived.
Input
The first line contains the number of buffalos (). The -th of the next lines contains two integers and (), the position of buffalo . No two buffalos share a position.
The next line contains the number of settlers (). The -th of the next lines contains two integers and (), the post of the -th settler. All are different, and all are different.
Output
Print lines. Line contains the number of buffalos claimed by the -th settler when he arrived.
Hint

The picture shows the pasture of the first example after all four settlers have arrived. The gray disks are buffalos, and the white circles are fence posts.