题解:P11073 Game King

· · 题解

题意

给定一张有向图,求出所有 x,满足对于所有 y,x 能到 y 或 y 能到 x。

思路

缩点

很明显,在一个强连通分量中,所有点都可以互相到达。所以按强连通分量缩点,将图变成一张 DAG(有向无环图)。

拓扑排序

在 DAG 上,只能到达拓扑序比自己大的节点,所以仅需判断是否能到达所有拓扑序比自己大的点且被所有拓扑序比自己小的点到达即可。建一张正图,一张反图,分别跑一次拓扑排序,如果一个点弹出队列时队列为空,就相当于能到达比自己拓扑序大的所有点。

问题修正

但是,这样会出问题,反图的拓扑序不一定是将正图的拓扑序反过来得到的,这就会导致有些点被多算。解决方法也很简单,设 x 为没有入队的节点数,能到的点即为出队后的 x。在判断答案时,加上一个条件:能到的点数为总点数减一(减掉自己),就做完了。

代码

#include <bits/stdc++.h>
using namespace std;
int n, m, id, tot, dfn[1000005], low[1000005], scc[1000005], in[1000005], out[1000005], cnt[1000005];
vector<int> g[1000005], r[1000005], h[1000005], v[1000005];
bool inst[1000005], f1[1000005], f2[1000005];
stack<int> st;
void tarjan(int x){
    dfn[x] = low[x] = ++tot;
    st.push(x);
    inst[x] = 1;
    for(auto i : g[x]){
        if(!dfn[i]){
            tarjan(i);
            low[x] = min(low[x], low[i]);
        }
        else if(inst[i]) low[x] = min(low[x], dfn[i]);
    }
    if(dfn[x] == low[x]){
        id++;
        while(1){
            int t = st.top();
            st.pop();
            inst[t] = 0;
            scc[t] = id;
            v[id].push_back(t);
            if(t == x) break;
        }
    }
}
int main(){
    cin >> n >> m;
    for(int i = 1; i <= m; i++){
        int x, y;
        cin >> x >> y;
        g[x].push_back(y);
    }
    for(int i = 1; i <= n; i++){
        if(!dfn[i]) tarjan(i);
    }
    for(int i = 1; i <= n; i++){
        for(auto j : g[i]){
            if(scc[i] == scc[j]) continue;
            r[scc[i]].push_back(scc[j]);
            h[scc[j]].push_back(scc[i]);
            in[scc[j]]++;
            out[scc[i]]++;
        }
    }
    int xxx = id;
    queue<int> q;
    for(int i = 1; i <= id; i++){
        if(!in[i]) q.push(i);
    }
    while(!q.empty()){
        int t = q.front();
        q.pop();
        if(q.empty()) f1[t] = 1;
        xxx--;
        cnt[t] += xxx;
        for(auto i : r[t]){
            in[i]--;
            if(!in[i]) q.push(i);
        }
    }
    for(int i = 1; i <= id; i++){
        if(!out[i]) q.push(i);
    }
    xxx = id;
    while(!q.empty()){
        int t = q.front();
        q.pop();
        if(q.empty()) f2[t] = 1;
        xxx--;
        cnt[t] += xxx;
        for(auto i : h[t]){
            out[i]--;
            if(!out[i]) q.push(i);
        }
    }
    int ans = 0;
    for(int i = 1; i <= n; i++) if(f1[scc[i]] && f2[scc[i]] && cnt[scc[i]] + 1 == id) ans++;
    cout << ans;
    return 0;
}