hdu 3038

题目链接

关于并查集系列问题的解法链接

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
using namespace std;

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

int find(int x)
{
    if(x!=pre[x])
    {
        int f=pre[x];
        pre[x]=find(pre[x]);
        sum[x]+=sum[f];        //同时记录答案,差势积累到根节点
    }
    return pre[x];
}

int main()
{
    int N,M;
    while(cin>>N>>M)
    {
        for(int i=0; i<=N; i++)
        {
            pre[i]=i;
            sum[i]=0;
        }
        int cnt=0;
        while(M--)
        {
            int l,r,m;
            cin>>l>>r>>m;
            l--;//在写区间和个数问题时一般是计算左下标-1到右上标的距离
            int xx=find(l);
            int yy=find(r);
            if(xx==yy)
            {
                if(sum[l]-sum[r]!=m)
                    cnt++;
            }
            else
            {
                /*
                pre[xx]=yy;
                sum[xx]=sum[r]-sum[l]+m;
                cout<<sum[r]-sum[l]<<endl;
                */
                if(xx<yy)                      //作图可以看出答案假设xx,yy在r,l的右边通过公式可以计算出答案
                {
                    pre[xx]=yy;
                    sum[xx]=sum[r]-sum[l]+m;
                }
                else
                {
                    pre[yy]=xx;
                    sum[yy]=sum[l]-sum[r]-m;
                }

            }
        }

        cout<<cnt<<endl;
    }
    return 0;
}


猜你喜欢

转载自blog.csdn.net/qq_40861069/article/details/81174090