您的位置:首页 > 其它

HDU 2120 Ice_cream's world I

2014-08-01 12:56 323 查看
并查集应用之 判断环:依次输入每条边,当边的两个点在同一个集合时,环数加一,否则合并。

#include<cstdio>
#include<cstring>
#include<iostream>
#include<iomanip>
#include<queue>
#include<cmath>
#include<stack>
#include<map>
#include<vector>
#include<set>
#include<algorithm>
using namespace std;
typedef long long LL;
const int int_max = 0x07777777;
const int int_min = 0x80000000;
int n, m;
int mymap [1100][1100];
int root[1100];
int find (int x){
while(x!=root[x]){
x = root[x];
}
return x;
}
void combine (int x, int y){
int xx = find(x);
int yy = find(y);
if(xx!=yy){
root[yy] = xx;
}
}
int main(int argc, const char * argv[])
{
while(scanf("%d %d",&n, &m)!=EOF){
memset(mymap, 0, sizeof(mymap));
for(int i = 0; i < n; i++) root[i] = i;
int result = 0;
for(int i = 0; i < m; i++){
int x,y;
cin >> x >> y;
if(find(x)==find(y)){
result++;
}else{
combine(x, y);
}
}
cout << result << endl;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: