并查集应用之 判断环:依次输入每条边,当边的两个点在同一个集合时,环数加一,否则合并。
#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;
}
}