并查集 擒贼先擒王//解密犯罪团伙

写个比较一般的并查集过渡:

题意:有n个罪犯,警察给了m个条件,找出一共有多少个团伙。

样例输入:

10 9
1 2
3 4
5 2
4 6
2 6
8 7
9 7
1 6
2 4

样例输出:3

分割线:


#include<bits/stdc++.h>
using namespace std;
const int maxn = 10010;
int par[maxn];
void Init(int n){
   for(int i = 1; i <= n;++ i)
   par[i] = i;	
}

int Find(int x){
	return x == par[x]?x:Find(par[x]); 
}

void Unite(int x,int y){
    x = Find(x);
	y = Find(y);
	   if(x != y)
		par[y] = x;

}

int main(){
	int x,y,n,m;
	int sum = 0;
	scanf("%d %d",&n,&m);
	Init(n);
	for(int i = 1;i <= m;++i){
		cin>>x>>y;
		Unite(x,y);
	}
	
	for(int i = 1;i<=n; ++i)
	if(par[i] == i)
	sum++;
	cout<<sum;
	return 0;
} 

模板,没啥说的,找祖宗。

最后:

programming is the most fun you can have with your clothes on.

猜你喜欢

转载自blog.csdn.net/A_Pathfinder/article/details/82761479