思路: 并查集
分析:
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;
}
本文提供了一种使用并查集解决UVA1160问题的方法。通过并查集来判断元素间的关系,并进行相应连接操作,实现对输入数据的有效处理。代码实现了对输入数据的读取、并查集的初始化、查找及合并等核心功能。
198

被折叠的 条评论
为什么被折叠?



