题目的大致意思就是要拒绝会使图中出现环的边,用一个并查集来进行维护,如果是同一个连通分量中的就拒绝。
#include "stdio.h"
#include "string.h"
#include "math.h"
#include <string>
#include <queue>
#include <stack>
#include <vector>
#include <map>
#include <algorithm>
#include <iostream>
using namespace std;
#define MAXM 1
#define MAXN 1
#define max(a,b) a > b ? a : b
#define min(a,b) a < b ? a : b
#define Mem(a,b) memset(a,b,sizeof(a))
int Mod = 1000000007;
double pi = acos(-1.0);
double eps = 1e-6;
typedef struct{
int f,t,w,next;
}Edge;
Edge edge[MAXM];
int head[MAXN];
int kNum;
typedef long long LL;
void addEdge(int f, int t, int w)
{
edge[kNum].f = f;
edge[kNum].t = t;
edge[kNum].w = w;
edge[kNum].next = head[f];
head[f] = kNum ++;
}
int a, b;
int father[100005];
void init(){
for(int i = 0; i <= 100000; i ++){
father[i] = i;
}
}
int find(int x){
int p = x;
while(father[x] != x) x = father[x];
for(int q = p; q != x; q = p){
p = father[q];
father[q] = x;
}
return x;
}
void Union(int x, int y){
if(x < y){
father[y] = x;
}
else{
father[x] = y;
}
}
int main()
{
int ans = 0;
// freopen("d:\\test.txt", "r", stdin);
while(cin>>a){
ans = 0;
if(a == -1) continue;
cin>>b;
init();
int p = find(a), q = find(b);
Union(p, q);
while(cin>>a){
if(a == -1) break;
cin>>b;
p = find(a), q = find(b);
if(p == q) ans ++;
else Union(p, q);
}
cout<<ans<<endl;
}
return 0;
}