我的代码如下
#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,不知道为什么。。。