并查集-How Many Answers Are Wrong(hdu3038)

题意:

现给出n个数字组成的序列,编号为1~n;

给出m个查询,每个查询的答案由a,b,s三个数组成,表示从第a个数加到第b个数的和为s(对于a~b之间的和是s,其实可以理解成b比a-1大s);

但是其中有一些是有矛盾的(或者说错误的),求错误的查询答案有多少个。

题解:

经典的带权并查集问题;
1.sum[x]表示x-1到f[x]的和
2.sum[x] = sum[x]+sum[f[x]];//find_head()

3.并查集联合父节点不同sum[fb] = s+sum[a]-sum[b];

4.并查集联合父节点相同if(sum[b]-sum[a]) != s) return true;

  #include <iostream>
    #include <cstdio>
    #include <cstring> 
    using namespace std;
    const int N = 200005;
    int f[200005];
    int sum[200005];
    int find_head(int x)
    {
        int fx = x;
        if(x != f[x])
        {
            fx = find_head(f[x]);
            sum[x] = sum[x]+sum[f[x]];
            f[x] = fx;
        }
        return fx;
    }
    bool union_set(int a, int b, int s)//假话return true
    {
        int fa = find_head(a);
        int fb = find_head(b);
        if(fa != fb)
        {
            f[fb] = fa;
            sum[fb] = s+sum[a]-sum[b];
            return false;
        } 
        if((sum[b]-sum[a]) != s) return true;
        return false;
    }
    int main()
    {
        int n, m;
        while(scanf("%d%d",&n,&m) == 2)
        {
            int ans = 0;
            memset(sum, 0, sizeof(sum));
            for(int i = 0; i <= n; i++)
            {
                f[i] = i;
            }
            while(m--)
            {    
                int a, b, s;
                scanf("%d%d%d", &a,&b,&s);
                a--; //对于a~b之间的和是s,其实可以理解成b比a-1大s
                if(union_set(a, b, s))
                {
                    ans++;
                } 
            }
            cout<<ans<<endl;
        }
    
        return 0;
    }

猜你喜欢

转载自blog.csdn.net/weixin_43863650/article/details/84786105