Why Did the Cow Cross the Road 6
InterviewTime limit2sMemory limit512 MB
Given an N x N grid of pastures, some adjacent pairs blocked by roads, and K cows on distinct cells, count the pairs of cows that cannot reach each other without crossing a road.
- Level
Medium5 of 10
- Topics
- Graph, BFS, Union-find, Implementation
- Solved
- No attempts yet
Problem
The reason the cow crossed the road is simply that there are so many roads. John's farm has so many roads that a cow can hardly move around without crossing one.
John's farm was recently reorganized. It is now an grid of small square pastures (). A cow can usually walk freely between two adjacent pastures, but some adjacent pairs are separated by a road that the cow must cross to go between them. A tall fence surrounds the farm, so no cow ever leaves it.
There are cows on John's farm (, ), each in a different pasture. Some pairs of cows cannot meet unless one of them crosses a road. Count how many such pairs there are.
Input
The first line contains , , and .
Each of the next lines describes one road. A road joins two pastures that are adjacent vertically or horizontally, and it is given as (row, column, row, column). Every number is between and , inclusive.
Each of the next lines gives the position of one cow as a row and a column.
Output
Print the number of pairs of cows that cannot meet without crossing a road.