Club Room Project (Large)
Time limit1sMemory limit512 MB
For each action, remove all walls between rooms x and y; print how many connected room blocks remain.
- Level
Medium4 of 10
- Topics
- Union-find, Array
- Solved
- No attempts yet
Problem
Byeongchan wants a club room, and the office gave him a chance to take one of rooms. The building is a single straight corridor with rooms in a row. The leftmost room is room 1, the numbers increase by one to the right, and the rightmost room is room . Between every pair of neighboring rooms stands one wall that separates them.
Other people want a club room too, but there were enough rooms, so Byeongchan was not worried. Then the Big Jongbin villain showed up and started knocking down the walls of the building. The villain follows these rules.
- The villain picks two rooms with and knocks down every wall between room and room .
- When the wall between two rooms falls, the two rooms become one room.
- A wall that is already gone is skipped.
- The villain does not want the building to collapse, so the wall on the left side of room 1 and the wall on the right side of room , the two walls that face the outside, are never knocked down.
As the number of club rooms dropped, Byeongchan got nervous. Given the number of rooms and the number of actions , count the club rooms that remain after all actions are done.
Input
The first line contains a positive integer (), the number of club rooms. The second line contains a non-negative integer (), the number of actions the villain takes. Each of the next lines contains one action as two positive integers and (). One action knocks down every wall between room and room .
The villain is clumsy, so the same action can appear several times.
Output
Print on one line the number of club rooms that remain after all actions are done.
Hint
Suppose and the actions are and then . The first action joins rooms 1 and 2, so the rooms are , , , . The second action joins rooms 2, 3 and 4, so the rooms are , . Two club rooms remain.