题解:AT_abc392_e [ABC392E] Cables and Servers

· · 题解

第一次写题解,各位大佬多多包涵QAQ

题目中 m 条边会产生 d(d可能为0) 个连通块。我们的任务是以最少操纵步骤将连通块相连,那么每次操作都必须将一条无意义的边变得有意义,显然最少操作数为 d-1。

简单讲及:将一条 (u,v)的边,满足 u 到 v 存在不通过此边的路径,及此边在环中。拆开此边,连向 u 无法到达的一点,及未被联通的连通块中一点。 操作如下

  1. 建图并找到所有连通块及其代表点,队列存下
  2. 遍历连通块,找到无意义的边拆开,与代表点相连,此代表点出队(此处不必真连,直接输出)
  3. 代码如下
#include <bits/stdc++.h>
using namespace std;

const int N=2e5+5;
typedef long long ll;

int n,m,cnt,diam[N],dfn[N],tot,now;
bool vis[N];
vector<pair<int,int>> g[N];
queue<int> node;

void dfs1(int u){
    vis[u]=true;
    for(auto v:g[u]){
        if(vis[v.first]) continue;
        dfs1(v.first);
    } 
}
void dfs2(int u,int fa){
    dfn[u]=++tot;
    bool flag=false;
    for(auto v:g[u]){
        if(v.first==fa && !flag){//可能有多条(u,fa)的边 
            flag=true;
            continue;
        }
        if(!dfn[v.first]) dfs2(v.first,u);
        else if(dfn[v.first]<=dfn[u]){
            cout<<v.second<<" "<<v.first<<" ";
            if(node.front()!=now){
                cout<<node.front()<<endl;
                node.pop();
            } 
            else {//注意不能是自己的代表点 
                int x=node.front();node.pop();
                cout<<node.front()<<endl;node.pop();
                node.push(x);
            }
        }
        if(node.size()<=1) exit(0);//不是<=0才停 
    } 
}

int main() {
    cin>>n>>m;
    for(int i=1;i<=m;i++){
        int u,v;
        cin>>u>>v;
        g[u].push_back({v,i});
        if(u!=v) g[v].push_back({u,i});
    }
    for(int i=1;i<=n;i++){
        if(!vis[i]){
            diam[++cnt]=i;
            node.push(i);
            dfs1(i);
        }
    }
    cout<<cnt-1<<endl;
    for(int i=1;i<cnt;i++){
        now=diam[i];
        dfs2(diam[i],0);
    } 
    return 0;
}

这道题告诉我们只要努力,无意义的边脚料,也能成为整体的顶梁柱。