hdu3038 并查集加权问题

我的代码如下

#include<bits/stdc++.h>
using namespace std;
#define ll long long
int root[200100], res[200100];

int Z(int x)
{
	if(root[x]==x) return x;
	int cnt=root[x];
    root[x]=Z(root[x]);
    res[x]+=res[cnt];
    return root[x];
}
int main()
{
	int n, m;
	while(scanf("%d%d",&n,&m)!=EOF)
	{
		for(int i=0;i<=n;++i) root[i]=i;
		memset(res,0,sizeof(res));
		long long sum=0;
		for(int i=0;i<m;++i)
		{
			int z, y, k;
			scanf("%d%d%d",&z,&y,&k);
			z--; 
			int rootz, rooty;
			rootz=Z(z);
			rooty=Z(y);
			if(rootz==rooty)
			{
				if(res[y]-res[z]!=k) sum++;
			} 
			else
			{
				root[rooty]=rootz;
				res[rooty]=k-res[y]+res[z];
			}
		}
		printf("%lld\n",sum);
	}
	return 0;
}

这里我要说明一下Z()这个函数,一开始我不是这样写的,我觉得还要写一个cnt太麻烦了,所以我就先求了res[x]的值,但是显然,这是不对的,错误代码如下

	res[x]+=res[root[x]];
	root[x]=Z(root[x]);
	return root[x];

为什么不对呢,一组数据就可以说明,
X 5 3 1
root 3 1 1
这就很明显,res[5]=res[5]+res[3]+res[1],但是错误代码则是res[5]+res[3]所以提醒一下自己吧
还有一个值得一提,我这个题一开始数组开小了,所以它一直显示tle,不知道为什么。。。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值