题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=3038

借鉴博客:https://blog.csdn.net/dextrad_ihacker/article/details/51016017

代码:

#include<iostream>
using namespace std;
const int maxn=200005;
int pre[maxn];
int sum[maxn];
int n,m;
void init()
{
	for(int i=0;i<maxn;i++)
	{
		pre[i]=i;
		sum[i]=0;
	}
}
int find(int x)
{
	if(pre[x]!=x) 
	{
		int f=pre[x];
		pre[x]=find(pre[x]);
		sum[x]+=sum[f]; 
	}
	return pre[x];
}
int main()
{
	while(~scanf("%d%d",&n,&m))
	{
		int ans=0;
		init();
		int a,b,v;
		while(m--)
		{
			cin>>a>>b>>v;
			a--;
			int x=find(a);
			int y=find(b);
			if(x!=y)
			{
				pre[x]=y;
				sum[x]=sum[b]-sum[a]+v;
			}
			else
			{
				if(sum[a]-sum[b]!=v) ans++;
			}
		} 
		cout<<ans<<endl;
	}
	return 0;
 } 

 

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐