标签:
Description
Input
Output
Sample Input
10 5
1 10 100
7 10 28
1 3 32
4 6 41
6 6 1
Sample Output
1
思路
1.若 a 和 b 同属一个集合,那么需判断[a, b]区间和是否为s。

if(sum[b] - sum[a] != s) ans++;
2.若 a 和 b 不同属一个集合,把b的父亲接在a的父亲上。

sum[pb] = -sum[b]+s+sum[a];
#include<stdio.h>
#include<string.h>
const int maxn = 200005;
int fa[maxn],sum[maxn];
int find(int x)
{
if (fa[x] != x)
{
int tmp = fa[x];
fa[x] = find(fa[x]);
sum[x] += sum[tmp];
}
return fa[x];
}
int main()
{
int N,M;
while (~scanf("%d%d",&N,&M))
{
int res = 0;
for (int i = 1; i <= N; i++) fa[i] = i,sum[i] = 0;
while (M--)
{
int a,b,v;
scanf("%d%d%d",&a,&b,&v);
a--;
int pa = find(a),pb = find(b);
if (pa == pb)
{
if (sum[b] - sum[a] != v) res++;
}
else
{
fa[pb] = pa;
sum[pb] = -sum[b] + v + sum[a];
}
}
printf("%d\n",res);
}
return 0;
}
HDU 3038 How Many Answers Are Wrong(带权并查集)
标签:
原文地址:http://www.cnblogs.com/zzy19961112/p/5914753.html