P8359 [SNOI2022] 垃圾回收

· · 题解

一道很裸的并查集.倒叙放入即可!!!!

唯一要注意的是 unsigned long long

#include<bits/stdc++.h>
using namespace std;
long long large[1000001];
int father[1000001],a[1000001],b[1000001],n,m,q;
int del[1000001],deled;
bool use[1000001];
bool fi[1000001];
unsigned long long ans=0;
int get_father(int x)
{
    if(father[x]==x)
    return x;
    else
    return father[x]=get_father(father[x]);
}
int last_ki;
int main()
{
//  freopen("garbage.in","r",stdin);
//  freopen("garbage.out","w",stdout);
    scanf("%d%d%d",&n,&m,&q);
    for(int i=1;i<=m;i++)
    {
    scanf("%d%d",&a[i],&b[i]);      
    }
    for(int i=1;i<=q;i++)
    {
        char we[15];
        scanf("%s",&we);
//      del[i]=0;
        if(we[0]=='D')
        {
            int x;
            scanf("%d",&x);
            del[i]=x;
            use[x]=true;
        }
        else
        del[i]=-1;
    }
    last_ki=q+1;
    for(int i=1;i<=n;i++)
    scanf("%lld",&large[i]);
    for(int i=1;i<=n;i++)
    {
    father[i]=i;    
    }
    for(int i=1;i<=m;i++)
    if(use[i]==false)
    {
        int x=get_father(a[i]),y=get_father(b[i]);
        if(y==1)
        swap(x,y);
        if(x==y)
        continue;
        large[x]+=large[y];
        father[y]=x;            
    }
//  for(int i=1;i<=n;i++)
//  {
//  cout<<i<<" "<<father[i]<<" "<<large[get_father(i)]<<endl;       
//  }
    for(int i=q;i>=1;i--)
    {
        ans+=large[1];
    //  cout<<large[1]<<endl;
        if(del[i]==-1)
        {
            last_ki=i;
        }
        else
        {
            int x=get_father(a[del[i]]),y=get_father(b[del[i]]);
        //  cout<<a[del[i]]<<" "<<b[del[i]]<<endl;
            if(x==y)
            continue;
            if(y==1)
            swap(x,y);
            if(x==1)
            {
                ans+=large[y]*(last_ki-i);
        //      cout<<y<<" "<<large[y]<<" "<<i<<" "<<last_ki<<endl;
            }
            if(x==y)
            continue;
            large[x]+=large[y];         
            father[y]=x;
        }
    }
    for(int i=1;i<=n;i++)
    if(fi[get_father(i)]==false&&get_father(i)!=1)
    {
        fi[get_father(i)]=true;
        ans+=large[get_father(i)]*(last_ki);
    }
    cout<<ans+large[1];
}