并查集模板

#include<iostream>
#include<cstdio>
using namespace std;

int f[102];

int found(int x){
	return f[x] = f[x] == x ? x : found(f[x]);
//	if(x == f[x])
//	    return x;
//	else{
//		f[x] = found(f[x]);
//		return f[x];
//	}
}

int main(){
	int i,j;
	for(i=0; i<10; i++)
	    f[i] = i;
	for(int k=0; k<5; k++){
		scanf("%d%d",&i,&j);
		int x = found(i);
		int y = found(j);
		if(x != y)
		    f[x] = y;
	}
	for(i=0; i<10; i++)
	    printf("%d %d
",i,found(i));
	return 0; 
}
原文地址:https://www.cnblogs.com/jxgapyw/p/5289925.html