(并查集 添加关系)How Many Answers Are Wrong --Hdu --3038

链接:

http://acm.hdu.edu.cn/showproblem.php?pid=3038

http://acm.hust.edu.cn/vjudge/contest/view.action?cid=82830#problem/D

代码:

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<math.h>
#include<algorithm>
#include<iostream>
#include<vector>
using namespace std;

#define N 200005

int n, m, f[N], r[N];

int Find(int x)
{
    int k=f[x];
    if(x!=f[x])
    {
         f[x]=Find(f[x]);
         r[x]=r[x]+r[k];
    }

    return f[x];
}

int main()
{
    while(scanf("%d%d", &n, &m)!=EOF)
    {
        int ans=0, i, a, b, t, fa, fb;

        for(i=0; i<=n; i++)
        {
            f[i]=i;
            r[i]=0;
        }

        for(i=0; i<m; i++)
        {
            scanf("%d%d%d", &a, &b, &t);
            a--;
            fa=Find(a), fb=Find(b);

            if(fa!=fb)
            {
                 f[fa]=fb;
                 r[fa]=r[b]-r[a]-t;
            }
            else
            {
                if(t!=r[b]-r[a])
                    ans++;
            }
        }

        printf("%d
", ans);
    }

    return 0;
}