题目:
链接:点击打开链接
算法:
赤裸裸的并查集。
代码:
#include<iostream> #include<cstdio> #include<cstring> using namespace std; int n,m; int root[1010]; int find(int x) { int r = x; while(root[r] != r) r = root[r]; return r; } void merge(int x,int y) { int fx = find(x); int fy = find(y); if(fx != fy) root[fx] = fy; } int main() { //freopen("input.txt","r",stdin); int a,b; int cnt; while(scanf("%d",&n) != EOF && n) { memset(root,0,sizeof(root)); for(int i=1; i<=n; i++) root[i] = i; scanf("%d",&m); for(int i=1; i<=m; i++) { scanf("%d%d",&a,&b); merge(a,b); } cnt = -1; for(int i=1; i<=n; i++) { if(root[i] == i) cnt++; } printf("%d\n",cnt); } return 0; }
原文地址:http://blog.csdn.net/u013147615/article/details/26289401