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


}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章