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;如果不等,则有冲突。

你可能感兴趣的:(HDU 3074 带权并查集)