强连通分量

受欢迎的牛

\(tarjan将强连通分量缩点转化成拓扑图的原理看\)这里

\(最受欢迎的牛必然是拓补图的终点,且若图中不止一个终点,必然没有某个牛被所有牛欢迎\)

#include <bits/stdc++.h>
using namespace std;
#define IO ios::sync_with_stdio(false);cin.tie(0); cout.tie(0)
inline int lowbit(int x) { return x & (-x); }
#define ll long long
#define pb push_back
#define PII pair<int, int>
#define x first
#define y second
#define inf 0x3f3f3f3f
const int N = 10010, M = 50010;
int n, m;
int h[N], e[M], ne[M], idx;
int dfn[N], low[N], timestamp;
int stk[N], top;
bool in_stk[N];
int id[N], scc_cnt, Size[N];
int dout[N];

void add(int a, int b) {
    e[idx] = b, ne[idx] = h[a], h[a] = idx++;
}

void tarjan(int u) {
    dfn[u] = low[u] = ++timestamp;
    stk[++top] = u, in_stk[u] = true;
    for (int i = h[u]; ~i; i = ne[i]) {
        int j = e[i];
        if (!dfn[j]) {
            tarjan(j);
            low[u] = min(low[u], low[j]);
        }
        else if (in_stk[j]) low[u] = min(low[u], dfn[j]);
    }
    if (dfn[u] == low[u]) {
        ++scc_cnt;
        int y;
        do {
            y = stk[top--];
            in_stk[y] = false;
            id[y] = scc_cnt;
            Size[scc_cnt]++;
        } while (y != u);
    }
}

int main() {
    IO;
    cin >> n >> m;
    memset(h, -1, sizeof h);
    while (m--) {
        int a, b;
        cin >> a >> b;
        add(a, b);
    }
    for (int i = 1; i <= n; ++i) 
        if (!dfn[i]) tarjan(i);

    for (int i = 1; i <= n; ++i) 
        for (int j = h[i]; ~j; j = ne[j]) {
            int k = e[j];
            int a = id[i], b = id[k];
            if (a != b) dout[a]++;
        }
    
    int zeros = 0, sum = 0;
    for (int i = 1; i <= scc_cnt; ++i)
        if (!dout[i]) {
            zeros++;
            sum += Size[i];
            if (zeros > 1) {
                sum = 0;
                break;
            }
        }
    cout << sum << '\n';
    return 0;
}
posted @ 2021-02-20 01:42  phr2000  阅读(40)  评论(0编辑  收藏  举报