【C - How Many Tables】

Ideas:

  • Disjoint-set of very simple matter, there are several requirements Unicom block, the last head of -1 the number of elements is chant.

Code:

  • 0ms 1416kB
//0ms		1416kB


#include <iostream>
#include <cstring>
#include <cstdio>

using namespace std;

const int maxn = 1005;

int N,M;
int ans;
int par[maxn];

void INIT(){
	memset(par , -1 , sizeof(par));
	ans = 0;
	return ;
}

int FIND(int i){
	return par[i] == -1 ? i : par[i] = FIND(par[i]);
}

void UNION(int l,int r){
	int parl = FIND(l);
	int parr = FIND(r);
	if(parr != parl)
		par[parr] = parl;
	return ;
}

int main(){
	int T;cin>>T;
	while(T--){
		INIT();
		scanf("%d%d" , &N , &M);
		while(M--){
			int l,r;
			scanf("%d%d" , &l , &r);
			UNION(l , r);
		}
		for(int i=1;i<=N;i++)
			if(par[i] == -1)
				ans++;
		printf("%d\n" , ans);
	}
	return 0;
}

Guess you like

Origin blog.csdn.net/flash403/article/details/94321845