Ant Colony
InterviewTime limit1sMemory limit1024 MB
Given a tree of unit tunnels on a grid, count the connected components left inside each query rectangle when the outside points are removed.
- Level
Medium5 of 10
- Topics
- Prefix sum, Sorting, Implementation
- Solved
- No attempts yet
Statement
The Integer Forest holds a large colony of tree ants. The Integer Forest is an infinite two-dimensional plane with a tree at every point that has integer coordinates. The colony consists of a number of integer points, and some pairs of adjacent points are connected by tunnels. Two points and are adjacent if , so the colony forms a graph. Tree ants are special because, besides living in trees, their colony is itself a tree: it is connected and has exactly tunnels, where is the number of points in the colony.
The researcher Anthony wants to run an experiment on the colony. He wants to know what happens when a rectangular area is cut off from the rest of the colony. His theory is that ants in different components of the graph form their own colonies and start wars against the others. A rectangle is the set of all integer points with and , where are given integers.
Anthony has not yet decided which rectangle to use, but he has several ideas. For each rectangle, determine how many components of the graph form inside the rectangle when it is cut off. Two points belong to the same component if one can reach the other through tunnels without visiting a point outside the rectangle. Anthony only cares about the components inside the cut-off rectangle and ignores the rest of the colony.
Input
The first line contains two integers and (), the size of the area the colony lives in.
The second line contains two integers and (, ), the number of points in the colony and the number of rectangles.
The next lines describe the tunnels. Each tunnel has one of two types:
h: points and are connected by a tunnel (, ).v: points and are connected by a tunnel (, ).
The next lines describe the rectangles. Each line contains four integers , , , and (, ). The rectangle consists of all points with and .
All coordinates of the colony satisfy and . It is guaranteed that the graph formed by the points and tunnels is a tree.
Output
Print lines, one for each rectangle, containing the number of components that form inside that rectangle when it is cut off.