Strange Power Lines
InterviewTime limit1sMemory limit512 MB
Keep a maximum subset of K lines with at most one per pole and no crossings, where pole labels are given in shuffled order. Output the number of lines to remove.
- Level
Medium7 of 10
- Topics
- Dynamic programming, Array, Sorting, Binary search
- Solved
- No attempts yet
Problem
Hyeonjeong, an elite road designer, maintains the power lines strung between the utility poles along a road. On each side of the road stand several utility poles, each with its own unique number. To supply as much electricity as possible to the town, she must remove as few unnecessary power lines as possible while making sure no two lines cross.
One day Hyeonjeong was dispatched to a neighborhood suffering from a power shortage. She headed to the neighborhood confident that she would solve its power problem, but she could not hide her shock. That neighborhood was stranger and more tangled than any she had ever seen. In an ordinary neighborhood the pole numbers are sorted in increasing order, but in the neighborhood she was dispatched to the pole numbers were in disarray. Worse, several power lines were dangerously connected to a single pole. In such cases, to prevent accidents, the number of power lines connected to one pole must be reduced to at most one.
Hyeonjeong wants to keep the number of removed power lines to a minimum in order to uphold her pride as an elite road designer. Tell her the minimum number of power lines she must remove.
Input
The first line gives the integers N and M, the numbers of utility poles on each side of the road.
The second line gives the numbers of the utility poles on the left side of the road as distinct integers between 1 and N inclusive.
The third line gives the numbers of the utility poles on the right side of the road as distinct integers between 1 and M inclusive.
The fourth line gives K, the number of power lines.
Starting from the fifth line, one line each gives the number of the utility pole connected to the left side of the road followed by the number of the utility pole connected to the right side. No two identical power lines are installed.
Output
Print the minimum number of power lines that must be removed.