LA3644(并查集,维护连通分量的集合)

  题目的大致意思就是要拒绝会使图中出现环的边,用一个并查集来进行维护,如果是同一个连通分量中的就拒绝。

  

  

#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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值