hdu 3047 Zjnu Stadium 带权并查集

题意:n个数,然后给出m个关系:A,B,x,表示B比A多x。问里面有多少个错误的冲突关系

将并查集里面的每一个集合看成一棵树,树根距离为0,rank[]表示离树根的距离,合并A,B时,假设A,B属于不同的树,那么就要合并这两棵树。合并方法参考点击打开链接

#include <map>
#include <set>
#include <queue>
#include <stack>
#include <vector>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>

using namespace std;

#define lson l, mid, rt << 1
#define rson mid + 1, r, rt << 1 | 1
#define pi acos(-1.0)
#define eps 1e-8
#define asd puts("sdasdasdasdasd");
typedef long long ll;
const int inf = 0x3f3f3f3f;
const int N = 200050;

int r[N], fa[N];
int n, m;

void init()
{
	for( int i = 1; i <= n; ++i )
	{
		fa[i] = i; 
		r[i] = 0;
	}
}

int dfs( int x )
{
	if ( x == fa[x] )
		return x;
	int ani = fa[x];
	fa[x] = dfs( fa[x] );
	r[x] += r[ani];
	return fa[x];
}

bool Union( int a, int b, int c )
{
	int x = dfs( a );
	int y = dfs( b );
	if( x == y )
	{
		if( r[a] + c == r[b] )
			return 1;
		else
			return 0;
	}
	fa[y] = x;
	r[y] = r[a] + c - r[b];
	return 1;
}

int main()
{
	while( ~scanf("%d%d", &n, &m) )
	{
		init();
		int cnt = 0;
		int a, b, x;
		while ( m-- )
		{
			scanf("%d%d%d", &a, &b, &x );
			if( !Union( a, b, x ) )
				cnt++;
		}
		printf("%d\n", cnt);
	}
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值