City and Campers 2
Practice
3.8 (41 votes)
Approved
Data structures
Disjoint set
Hard
Implementation
Open
Problem
90% Success 5080 Attempts 50 Points 2s Time Limit 256MB Memory 1024 KB Max Code

The campers turn against Alex after joining together!

Alex has split into N parts, and each of these N parts is wandering around the city aimlessly. You have to handle Q queries; which consist of two groups of Alex's finding each other and becoming one larger group. After each query, output the minimum difference between two groups. If there is only one group, output 0. At first, everyone is in their own group. What this means is that there are N groups, each of which contain 1 part of Alex.

Also note, if the two Alex's in the query are already in the same group, print the current answer, and skip merging the groups together.

Input:

The first line consists of two space separated integers, N and Q

The next Q line consists of two integers, A and B, meaning that the groups involving Alex A and Alex B find each other.

Output:

Output Q lines, the answer after each query.

Constraints:

1 <= N <= 105

1 <= Q <= 105

Please login to use the editor

You need to be logged in to access the code editor

Loading...

Please wait while we load the editor

Loading...
Results
Custom Input
Run your code to see the output
Submissions
Please login to view your submissions
Similar Problems
Points:50
1 votes
Tags:
Data StructuresDisjoint Data StructuresDisjoint SetHard
Points:50
5 votes
Tags:
AlgorithmsApprovedData StructuresDisjoint setHardOpen
Points:50
6 votes
Tags:
Data StructuresDisjoint Data StructuresDisjoint SetDisjoint setHard