計蒜課網站上課程《程序設計競賽入門》提到並查集思想,結合了次博主http://blog.csdn.net/dellaserss/article/details/7724401詳細的解答,我終於寫了第一道有關於並查集的程序。
此題目選自 http://www.jisuanke.com/course/8/364
<span style="font-size:24px;">#include<cstdio>
#include<iostream>
int fa[2000];
// father函數返回的是節點x的祖先節點
int father(int x) {
if (fa[x] != x) fa[x] = father(fa[x]);
return fa[x];
}
// 合併兩個節點所在集合,同時判斷兩個點之前是否在一個集合裏
// 函數返回true則之前兩個點不在一個集合中
bool join(int x, int y) {
int fx = father(x), fy = father(y);
if (fx != fy) {
fa[fx] = fy;
return true;
} else {
return false;
}
}
int main()
{
void init(int );
int n,m,ans;
while(~scanf("%d %d",&n,&m) && n+m)
{
ans = 0;
int a,b;
init(n);
for(int i =1;i<=n;i++)
{
scanf("%d %d",&a,&b);
if(join(a,b));
else ans++;
}
printf("%d\n",ans);
}
}
void init(int n) {
for (int i = 1; i <= n; ++i) fa[i] = i;
}</span>
第一次寫博客,不喜勿噴,謝謝。