题解:P8907 [USACO22DEC] Making Friends P

· · 题解

题意

对于一个 n 个点的图,有 m 条边,第 i 天第 i 个点会消失,并将它连向的边互相连接,即将他连向的那些点形成一个完全图。

思路

很明显通对于一个点 i 和它连向的点集 V_{i} 若 i 离开后最早会需要用到点集 V_{i} 的点就是 V_{i} 中的点的编号的最小值,所以我们考虑启发式合并,对于一个点 i 我们将它记录好答案后只将点集 V_{i} 放到 V_{i} 中编号最小的点的点集中即可。

这个过程中需要去重还需要排序,所以 set 即可。

代码

//Author:Kevin Z K Y
#include <bits/stdc++.h>
#define up(a,b,c) for(int (a)=(b);(a)<=(c);(a)++)
#define dn(a,b,c) for(int (a)=(b);(a)>=(c);(a)--)
#define fst first
#define sed second
using namespace std;
using ull = unsigned long long ;using ui = unsigned int ;
using ll = long long ;using hint = __int128 ;
using pii = pair<int,int> ;using pll = pair<ll,ll> ;
using vi = vector<int> ;using vl = vector<ll> ;
using vpi = vector<pii> ;using vpl = vector<pll> ;
using db = double ;namespace mystl{
    #define gc() getchar()
    ll qpow(ll a,ll b,const ll&p){if (a==0ll) return 0ll; ll c=1ll;
        while(b) { if(b & 1) c=a*c%p; a=a*a%p; b>>=1; } return c; }
    template<typename T>void read(T&x) {x=0; bool f=false; char ch;
        ch = gc(); while(ch<'0'||ch>'9') f |= ( ch=='-') , ch=gc();
        while(ch>='0'&&ch<='9') x=x*10+ch-'0' , ch=gc(); x=f?-x:x;}
    template<typename T>void write(T x){char s[40];short d=0;T y=x;
        if(x<0) putchar('-'),y=-y;if(x==0){ putchar('0'); return; }
        while(y){s[++d]=y%10+'0';y/=10;}while(d>0)putchar(s[d--]);}
    template<typename T>void wris(T x,char c){write(x);putchar(c);}
}using namespace mystl;
namespace my{
    const int N=(int)(2e5+5);
    set<int>a[N];
    void solve(){
        int n,m;cin>>n>>m;
        up(i,1,m){
            int x,y;cin>>x>>y;if(x==y)continue;
            a[min(x,y)].insert(max(x,y));
        }ll ans=0;up(i,1,n){
            if(a[i].size()==0)continue;
            int to=*(a[i].begin());
            ll frt=a[to].size(),p=a[i].size();
//          cout<<"set:\n";
//          for(int v:a[i])cout<<v<<' ';cout<<'\n';
//          for(int v:a[to])cout<<v<<' ';cout<<'\n';
            if(frt>p){
                for(int v:a[i])
                    if(v!=to)
                        a[to].insert(v);
            }
            else {
                for(int v:a[to])
                    a[i].insert(v);
                a[to].swap(a[i]);
            }
            auto it=a[to].find(to);
            if(it!=a[to].end()) 
                a[to].erase(it);
            a[i].clear();
//          cout<<i<<' '<<to<<'\n';
//          for(int v:a[to])cout<<v<<' ';
//          cout<<'\n';
            ans+=(1ll*a[to].size()-frt);
        }cout<<ans<<'\n';
    }
}
int main(){
//  freopen("","r",stdin);
//  freopen("","w",stdout);
    ios::sync_with_stdio(false);cin.tie(nullptr);cout.tie(nullptr);
    int _=1;while(_--)my::solve();return 0;
}