[CF999E] Reachability from the Capital – 强连通分量

\(n\) 座城市和 \(m\) 条单向道路,为了能让首都能够到达所有的城市,最少需要新修建多少新的单向道路?

Solution

答案为缩点后的分量图中除 \(S\) 所在分量外入度为 \(0\) 的分量数

#include <bits/stdc++.h>
using namespace std;

#define int long long
const int N = 1000005;

namespace scc {
    vector <int> g[N],scc[N];
    int ind,f[N],siz[N],dfn[N],low[N],vis[N],s[N],
        bel[N],top,tot,n,m,d[N];
    void make(int p,int q) {
        g[p].push_back(q);
    }
    void dfs(int p) {
        s[++top]=p;
        dfn[p]=low[p]=++ind;
        for(int i=0;i<g[p].size();i++) {
            int q=g[p][i];
            if(!dfn[q]) dfs(q), low[p]=min(low[p],low[q]);
            else if(!bel[q]) low[p]=min(low[p],dfn[q]);
        }
        if(dfn[p]==low[p]) {
            ++tot;
            for(int i=0;i!=p;) {
                i=s[top--];
                bel[i]=tot;
                scc[tot].push_back(i);
            }
        }
    }
    void solve(int _n) {
        n=_n;
        for(int i=1;i<=n;i++) if(!dfn[i]) dfs(i);
    }
}

using scc::g;
using scc::tot;
using scc::make;
using scc::bel;
int n,m,r,t1,t2,t3,d[N];

signed main() {
    ios::sync_with_stdio(false);
    cin>>n>>m>>r;
    for(int i=1;i<=m;i++) {
        cin>>t1>>t2;
        make(t1,t2);
    }
    scc::solve(n);
    for(int i=1;i<=n;i++) {
        for(int j:g[i]) {
            if(bel[i]!=bel[j]) ++d[bel[j]];
        }
    }
    int ans=0;
    for(int i=1;i<=tot;i++) {
        if(d[i]==0 && bel[r]!=i) ++ans;
    }
    cout<<ans;
}



原文链接: https://www.cnblogs.com/mollnn/p/12585933.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

    [CF999E] Reachability from the Capital - 强连通分量

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/338441

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年3月1日 下午11:37
下一篇 2023年3月1日 下午11:37

相关推荐