您的位置:首页 > 其它

hdu 3038 How Many Answers Are Wrong (带权并查集)

2014-05-21 16:55 281 查看
题目

[align=left]Input[/align]
Line 1: Two integers, N and M (1 <= N <= 200000, 1 <= M <= 40000). Means TT wrote N integers and FF asked her M questions.
Line 2..M+1: Line i+1 contains three integer: Ai, Bi and Si. Means TT answered FF that the sum from Ai to Bi is Si. It's guaranteed that 0 < Ai <= Bi <= N.
You can assume that any sum of subsequence is fit in 32-bit integer.
题意:n个数,m条信息,每条信息是 从a到b的和,为s,判断有多少条信息错误,

如果发现一条信息错误,就去掉这条信息,然后再往下看。 注意这些值可能有负的。

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn = 200000+10;
int bin[maxn], dist[maxn], ans;

int find(int x)
{
if(x==bin[x]) return x;
int tmp = bin[x];
bin[x] = find(bin[x]);
dist[x] += dist[tmp];
return bin[x];
}
void merge(int x, int y, int s)
{
int fx = find(x);
int fy = find(y);
if(fx == fy)
{
if(dist[y] != dist[x] + s)
ans++;
}
else
{
bin[fy] = fx;
dist[fy] = dist[x] - dist[y] + s;
}
}
int main()
{
int n, m, i, a, b, s;
while(~scanf("%d%d", &n, &m))
{
ans = 0;
for(i = 1; i <= n; i++)
{
bin[i] = i;
dist[i] = 0;
}
while(m--)
{
scanf("%d%d%d", &a, &b, &s);
a--;  //注意
merge(a, b, s);
}
printf("%d\n", ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: