HDU 3074 带权并查集

#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;
const int maxn = 5E4 + 10;
int f[maxn], a, b, x, n, m, Rank[maxn];
void init()
{
	for (int i = 0; i <= n; i++)
		f[i] = i, Rank[i] = 0;
}
int find(int x)
{
	if (x == f[x]) return f[x];
	int t = f[x];
	f[x] = find(f[x]);
	Rank[x] += Rank[t];
	return f[x];
}
bool Union(int x, int y, int m)
{
	int a = find(x), b = find(y);
	if (a == b)
	{
		if (Rank[x] + m != Rank[y])return false;
		else return true;
	}
	f[b] = a;
	Rank[b] = Rank[x] + m - Rank[y];
	return true;
}
int main(int argc, char const *argv[])
{
	while (~scanf("%d%d", &n, &m) && n + m)
	{
		init();
		int cnt = 0;
		for (int i = 0; i < m; i++)
		{
			scanf("%d%d%d", &a, &b, &x);
			if (!Union(a, b, x)) cnt++;
		}
		printf("%d\n", cnt);
	}
	return 0;
}


给出N个a b x 表示a与b有x的距离,求给出关系冲突的有多少。

带权并查集,root[i] 为i到树根的距离,合并A和B,设A树的根节点为rootA, 则root[rootA] = root[A]-root[B]+X;如果不等,则有冲突。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值