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

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


题目大意:有n次询问,给出a到b区间的总和,

问这n次给出的总和中有几次是和前面已经给出的数据中是矛盾的?

操作:  x y z 表示【x,y】的和为z


把区间【x,y】的和为z ,转化为 【1,x-1】,【1,y】的差为z,这样我们就可以用并查集方便地处理了。


num[x]表示 x到根节点的距离 

fa[x]表示x的根节点

合并时优先取较大的为根



#include <cstdio>
#include <cmath>
#include <cstring>
#include <string>
#include <algorithm>
#include <queue>
#include <map>
#include <set>
#include <vector>
#include <iostream>
using namespace std;

const double pi=acos(-1.0);
double eps=0.000001;

int fa[212345];
int num[212345];
int find(int x)
{
    if (fa[x]==x)    return x;
    int tmp=find(fa[x]);
    num[x]=num[x]+num[fa[x]];
    return fa[x]=tmp;
}
int main()
{

    int n,m;
    while(cin>>n>>m)
    {


        int ans=0;
        int x,y,z;
        for (int i=0; i<=n; i++) fa[i]=i,num[i]=0;
        for (int i=1; i<=m; i++)
        {
            scanf("%d%d%d",&x,&y,&z);
            x--;
            int fx=find(x);
            int fy=find(y);
            if (fx!=fy)
            {
                if (fx>fy)
                    fa[fy]=fx,num[fy]=num[x]-z-num[y];
                else
                    fa[fx]=fy,num[fx]=num[y]+z-num[x];
            }
            else
            {
                int sum=-num[y]+num[x];
                if (sum!=z) ans++;
            }
        }
        printf("%d\n",ans);
    }
    return 0;

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值