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

题目

Input
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,判断有多少条信息错误,

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

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstring>
 4 #include <algorithm>
 5 using namespace std;
 6 const int maxn = 200000+10;
 7 int bin[maxn], dist[maxn], ans;
 8 
 9 int find(int x)
10 {
11     if(x==bin[x]) return x;
12     int tmp = bin[x];
13     bin[x] = find(bin[x]);
14     dist[x] += dist[tmp];
15     return bin[x];
16 }
17 void merge(int x, int y, int s)
18 {
19     int fx = find(x);
20     int fy = find(y);
21     if(fx == fy)
22     {
23         if(dist[y] != dist[x] + s)
24             ans++;
25     }
26     else
27     {
28         bin[fy] = fx;
29         dist[fy] = dist[x] - dist[y] + s;
30     }
31 }
32 int main()
33 {
34     int n, m, i, a, b, s;
35     while(~scanf("%d%d", &n, &m))
36     {
37         ans = 0;
38         for(i = 1; i <= n; i++)
39         {
40             bin[i] = i;
41             dist[i] = 0;
42         }
43         while(m--)
44         {
45             scanf("%d%d%d", &a, &b, &s);
46             a--;  //注意
47             merge(a, b, s);
48         }
49         printf("%d\n", ans);
50     }
51     return 0;
52 }

 

 

posted @ 2014-05-21 16:55  水门  阅读(180)  评论(0编辑  收藏  举报