HDU 3038 How Many Answers Are Wrong (扩展并查集)

题意:每次告诉你区间LR的和为多少,然后有时的输入是有冲突的,问你有冲突的有几个

思路:不怎么会这个,这一类的并查集之前用的不是很多,有一篇讲的很好的博客(传送门),这里面讲解的向量偏移解决了我困惑多年的疑问,但换了个角度写就一直wa,很烦

代码:

#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;
typedef long long LL;
inline LL read()
{
    LL x=0,f=1;char ch=getchar();
    while(ch>'9'||ch<'0'){if(ch=='-')f=-1;ch=getchar();}
    while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
    return x*f;
}

const int maxn=200010;
int fa[maxn];
int sum[maxn];

int Find(int x)
{
    if(x!=fa[x]){
        int t=fa[x];
        fa[x]=Find(fa[x]);
        sum[x]+=sum[t];
    }
    return fa[x];
}

int main()
{
    int n,m;
    while(~scanf("%d%d",&n,&m)){
        for(int i=0;i<=n;i++){
            fa[i]=i;
            sum[i]=0;
        }
        int ans=0;
        while(m--){
            int a=read(),b=read(),w=read();
            a--;
            int rta=Find(a);
            int rtb=Find(b);
            if(rta==rtb){
                if(sum[a]-sum[b]!=w)ans++;
            }
            else{
                fa[rta]=rtb;
                sum[rta]=-sum[a]+sum[b]+w;
            }
        }
        printf("%d\n",ans);
    }
    return 0;
}

 

posted @ 2018-10-30 22:22  啦啦啦天啦噜  阅读(151)  评论(0编辑  收藏  举报