HDU-3038How Many Answers Are Wrong权值并查集

Posted ckxkexing

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HDU-3038How Many Answers Are Wrong权值并查集相关的知识,希望对你有一定的参考价值。

How Many Answers Are Wrong

题意:输入一连串的区间和,问和前面的矛盾个数;

思路:我在做专题,知道是并查集,可是还是不知道怎么做,学了一下权值并查集和大佬的优秀思路,感觉回了一点;

    具体就是 在并查集的基础上,加上val【】数组用来记录区间和,而原来的fa【】数组表示的是这个数能到达的最左边的下标;

   下面是ac代码

#include <cstdio>
#include <algorithm>
using namespace std;

const int maxn = 200005;
int val[maxn],fa[maxn],n,m,ans=0;//fa记录下标所能到达最左端(),val表示前缀和

void init(){
    for(int i=0;i<=n;i++)
    {
        fa[i] = i;
        val[i]=0;
    }
}

int find (int x)
{
    if(fa[x]==x)return x;
    else 
    {
        int fn = find(fa[x]);
        val[x] +=val[fa[x]];
        return fa[x] = fn;
    }
}
void uni(int a,int b,int s)
{
    int px = find(a);
    int py = find(b);
    if(px==py)                //只有左区间相同是才能比较
    {
        if(val[b]-val[a]!=s)ans++;
    }
    else
    {
        fa[py] = px;
        val[py] = val[a] + s - val[b];
    }
}
int main(){
    while(~scanf("%d%d",&n,&m))
    {
        init();
        ans = 0;
        for(int i=1;i<=m;i++)
        {
            int a,b,s;
            scanf("%d%d%d",&a,&b,&s);
            a--;
            uni(a,b,s);
        }
        printf("%d\n",ans);
    }
    return 0;
}

 

以上是关于HDU-3038How Many Answers Are Wrong权值并查集的主要内容,如果未能解决你的问题,请参考以下文章

hdu-3038 How Many Answers Are Wrong[并查集]

HDU3038 How Many Answers Are Wrong —— 带权并查集

HDU-3038-How Many Answers Are Wrong

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

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

HDU 3038 How Many Answers Are Wrong