HDU3038 How Many Answers Are Wrong

来源:互联网 发布:电信4g是什么网络模式 编辑:程序博客网 时间:2024/05/29 04:01

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=3038

题目和POJ那几道题类似,都是并查集向量偏移来做,关系也比较好推导,p[x].r表示的是x与根节点的差,下面就是推导关系了

附AC代码:

#include <iostream>#include <cstdio>#include <cstdlib>#include <cstring>#include <cmath>#include <algorithm>using namespace std;#define N 200010struct data{    int p, r;}p[N];int a[N];int find(int x){    int temp;    if (p[x].p != x){        temp = p[x].p;        p[x].p = find(temp);        p[x].r = p[x].r + p[temp].r;    }    return p[x].p;}int main(){    int n, m;    int x, y, s;    int r1, r2;    int ans;    while (scanf("%d%d", &n, &m) != EOF){        memset(a, -1, sizeof(a));        ans = 0;        for (int i = 1; i <= n; i++){            p[i].p = i;            p[i].r = 0;        }        for (int i = 0; i < m; i++){            scanf("%d%d%d", &x, &y, &s);            x--;            r1 = find(x); r2 = find(y);            if (r1 != r2){                p[r2].p = r1;                p[r2].r = p[x].r + s - p[y].r;            }            else{                if (p[y].r - p[x].r != s) ans++;            }        }        printf("%d\n", ans);    }    return 0;}


原创粉丝点击