Farmer's Field
Time limit1sMemory limit128 MB
Count placements of a c-by-d or d-by-c rectangle fully inside a field whose every row is one contiguous segment.
- Level
Medium7 of 10
- Topics
- Sliding window, Stack, Prefix sum, Two pointers
- Solved
- No attempts yet
Problem
Byteland is a rectangle meters wide and meters high. Byteasar is a farmer whose field is made of unit squares. In every horizontal layer (row), the squares that belong to the field form a single contiguous segment, although the field as a whole need not be connected from top to bottom.
The king of Byteland has decreed that every farmer must hand over a rectangular area meters wide and meters high, made of unit squares, to the crown. The rectangle may be placed in either orientation, so it occupies either columns by rows or columns by rows, and it must lie entirely inside the farmer's field. The king picks the position. Byteasar hopes there are many legal positions so that the greedy king cannot decide quickly.
Count how many positions the king may choose, that is, the number of placements of the required rectangle (in either orientation) that fit completely inside Byteasar's field. Two placements are the same position only when they cover exactly the same set of squares, so when the two orientations coincide and are counted once.
Write a program that:
- reads the description of Byteasar's field and the dimensions of the area demanded by the king,
- computes the number of valid positions of that area inside the field,
- writes the answer to standard output.
Input
The first line contains four integers , , and (): the width and height of Byteasar's field, followed by the width and height of the area demanded by the king.
Each of the next lines describes one horizontal layer of the field, from top to bottom, with two integers and (, , ). In that layer the field starts meters from the left border of Byteland and spans consecutive unit squares, so it occupies columns through . A value of means the layer contains no field squares.
Output
Print a single integer: the number of positions at which the -by- rectangle (in either orientation) fits completely inside Byteasar's field.
Hint

The figure shows the field described by the example input; the dark cells belong to the field.
If you use C++, be careful with STL containers given the size of the data; a careless choice can exceed the time or memory limit.