HDU 3038 how many answers are wrong(带权并查集)

很简单的题,找出各个节点与根节点的关系,并与输入的权值进行比较

#include<iostream>
using namespace std;
#define MAX 200005

struct num
{
	int father;
	int relationship;
}num[MAX];

void make_set(int N)
{
	for(int i=0;i<=N;i++)
	{
		num[i].father=i;
		num[i].relationship=0;
	}
}

int find_set(int x)
{
	if(x==num[x].father)
		return x;
	int temp=num[x].father;
	num[x].father=find_set(num[x].father);
	num[x].relationship=num[x].relationship+num[temp].relationship;
	return num[x].father;
}

void union_set(int fx,int fy,int a,int b,int weight)
{

	num[fy].father=fx;
	num[fy].relationship=num[a].relationship-num[b].relationship+weight;
	
	
}


void main()
{
	int N,K;
	int ans,weight,fx,fy,a,b;
	while(cin>>N>>K)
	{
		make_set(N);
		ans=0;
		while(K-- && cin>>a>>b>>weight)
		{
		a--;//半开区间内找关系,注意a--
		fx=find_set(a);
		fy=find_set(b);
		if(fx!=fy)
		{
			union_set(fx,fy,a,b,weight);
		}
		else
		{
			if(abs(num[a].relationship-num[b].relationship)!=weight)
				ans++;
		}
		}
		cout<<ans<<endl;
	}
	


}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值