Editorial - CHFCOVID

PROBLEM LINK:

Practice
Contest

Author: Adarsh Mandal

DIFFICULTY:

EASY-MEDIUM.

PREREQUISITES:

Disjoint Sets

PROBLEM:

This is a simple problem based on disjoint set union.

EXPLANATION:

This is a simple problem based on disjoint set union.

SOLUTIONS:

Setter's Solution
#include<bits/stdc++.h>
using namespace std;

int size[100005];
int parent[100005];

int get(int a){
	if(parent[a] != a){
		parent[a] = get(parent[a]);
	}
	return parent[a];
}

int get_size(int a){
	a = get(a);
	return size[a];
}

void union_(int a,int b){
	a =  get(a);
	b = get(b);
	if(a == b) return ;
	if(size[a] < size[b]){
		int temp = a;
		a  = b ;
		b = temp ;
	}
	parent[b] = a;
	size[a] += size[b];
}

int main(){
	ios_base::sync_with_stdio(false);
	cin.tie(0);
	int n,q;
	cin>>n>>q;
	for(int i = 1;i<=n;i++){
		size[i] = 1;
		parent[i] = i ;
	}

	while(q--){
		string s;
		cin>>s;
		if(s == "union"){
			int a,b;
			cin>>a>>b;
			union_(a,b);
		}
		if(s == "size"){
			int a;
			cin>>a;
			cout<<get_size(a)<<endl;
		}
	}
	
}