Algorithm


problem link- https://www.spoj.com/problems/LOSTNSURVIVED/

LOSTNSURVIVED - Lost and survived

 

On September 22, 2004, Oceanic Flight 815 crashed on a mysterious island somewhere in the pacific.

There actually were survivors in the crash, N survivors. The mysterious island kept on moving in space - time, so no rescue reached them.

Initially every survivor was on his own. But soon they realized there are these “The Others” (Scientists of damn Dharma Initiative) on this Island too.

So to protect themselves from mad Scientists they started uniting into groups after Dr. Shephard said “Live together or die alone”.

You have to handle Q queries; which consist of two survivors becoming friends and thereby uniting their respective groups into a larger group.

After each query, output the difference between the group of largest size and group of smallest size at that time.

If there is only one group, output 0. At first, everyone is in their own group.

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

Also do comment if you have watched Lost :-p

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

survivor A and survivor B became friends uniting there groups.

Output

Output Q lines, the answer after each query.

1<=N<=100000

1<=Q<=100000

Example

Input:
5 3
1 2
2 3
5 4

Output:
1
2
1

 

Code Examples

#1 Code Example with C++ Programming

Code - C++ Programming

#include <bits/stdc++.h>
using namespace std;
const int MAXN = (int)1e5+5;
int n;
int parent[MAXN];
int size[MAXN];
set<pair<int, int> > s;
void initialize(){
	for(int i = 1;i <= n; i++){
		parent[i] = i;
		size[i] = 1;
		s.insert(make_pair(1, i));
	}
}
int root(int i){
	while(i!=parent[i]){
		parent[i] = parent[parent[i]];
		i = parent[i];
	}
	return i;
}
bool find(int a, int b){
	return root(a) == root(b);
}
void union1(int a, int b){
	int root_a = root(a);
	int root_b = root(b);
	
	if(root_a == root_b)
		return;
	
	s.erase(make_pair(size[root_a], root_a));
	s.erase(make_pair(size[root_b], root_b));
	if(size[root_a] < size[root_b]){
		parent[root_a] = root_b;
		size[root_b]+=size[root_a];
		s.insert(make_pair(size[root_b], root_b));
	}else{
		parent[root_b] = root_a;
		size[root_a]+=size[root_b];
		s.insert(make_pair(size[root_a], root_a));
	}
}

int main(){
    cin>>n;
    initialize();
    int q;
    cin>>q;
    while(q--){
        int a, b;
        cin>>a>>b;
        union1(a, b);
        set<pair<int, int> >::iterator it1 = s.end();
        it1--;
        cout<<(it1->first-s.begin()->first)<<endl;
    }
	return 0;
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
5 3
1 2
2 3
5 4

Output

x
+
cmd
1
2
1
Advertisements

Demonstration


SPOJ Solution-Lost and survived-Solution in C, C++, Java, Python

Previous
SPOJ Solution - Test Life, the Universe, and Everything - Solution in C, C++, Java, Python