题解:AT_abc401_e [ABC401E] Reachable Set

· · 题解

[ABC401E] Reachable Set

题意

给你一个 N 个点的无向图,每次操作可以删去一个点及与它相连的边。问对于 k=1,2,\cdots,N,使得点 1 的可达点恰好为 1,2,\cdots,k 的最小操作次数为多少或判断无解。

思路

考虑满足点 1 的可达点为 1,2,\cdots,k 所需要满足的限制条件是什么。

  1. 点 1 可以到达 1,2,\cdots,k。

  2. 点 1 不能到达 k+1,k+2,\cdots,n。

于是对于限制一,我们可以维护一个并查集,对于每个新加入的点跟有连边且比它小的点进行合并。

因为每次合并两个连通块会减少一个连通块,所以当合并到点 k 时的合并次数恰好为 k-1 时,说明前 k 个点均在一个连通块中。

对于限制二,很显然最优方案即为删去与该连通块有连边的所有点。

于是我们可以维护一个 set,表示需要删去的点。当每次加入一个点时若 set 中包含该点,则删除(因为该点变为可达点了),然后再加入所有与它有连边且大于它的点。此时 set 的大小即为最少的操作次数。

代码

#include <bits/stdc++.h>
using namespace std;
int n,m,f[200005],tot;
int find(int x){
    if(f[x]!=x) f[x]=find(f[x]);
    return f[x];
}
void uni(int x,int y){
    x=find(x),y=find(y);
    if(x!=y) f[x]=y,tot++;
}
vector<int> t[200005];
set<int> er;
signed main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr),cout.tie(nullptr);
    cin>>n>>m;
    for(int i=1;i<=n;i++) f[i]=i;
    for(int x,y,i=1;i<=m;i++){
        cin>>x>>y;
        t[x].push_back(y);
        t[y].push_back(x);
    }
    for(int i=1;i<=n;i++){
        if(er.find(i)!=er.end()) er.erase(i);
        for(int v:t[i]) if(v>i) er.insert(v);
        else if(v<i) uni(i,v);
        if(i!=1&&tot!=i-1) cout<<-1<<endl;
        else cout<<er.size()<<endl;
    }
    return 0; 
}