点击打开链接uva 1160
思路: 并查集
分析:
1 看懂题目之和就是切菜了
代码:
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
const int MAXN = 100010;
int father[MAXN];
int find(int x){
if(father[x] != x)
father[x] = find(father[x]);
return father[x];
}
int main(){
int x , y , ans;
while(scanf("%d" , &x) != EOF){
scanf("%d" , &y);
for(int i = 0 ; i < MAXN ; i++)
father[i] = i;
father[x] = y;
ans = 0;
while(scanf("%d" , &x) && x != -1){
scanf("%d" , &y);
int fx = find(x);
int fy = find(y);
if(fx == fy)
ans++;
else
father[fx] = fy;
}
printf("%d\n" , ans);
}
return 0;
}