学校网络

AcWing-367-学校网络open in new window

分析

见《进阶指南》第416页。

实现

#include <iostream>
#include <cstring>
#include <vector>
#include <stack>
using namespace std;

const int N = 110, M = 10010;
struct edge {
    int to, next;
};
edge e[M];
int idx, head[N], in_deg[N], out_deg[N];
struct node {
    int u, v;
};
int n;
vector<node> rec;
int cnt, dfn[N], low[N];
stack<int> s;
bool in_stack[N];
int tot, scc[N];

void add_edge (int u, int v) {
    e[idx].to = v;
    e[idx].next = head[u];
    head[u] = idx ++;
}
void tarjan (int cur) {
    low[cur] = dfn[cur] = ++ cnt;
    s.push(cur);
    in_stack[cur] = true;
    for (int i = head[cur]; i != -1; i = e[i].next) {
        int to = e[i].to;
        if (dfn[to] == 0) {
            tarjan(to);
            low[cur] = min(low[cur], low[to]);
        } else if (in_stack[to] == true) {
            low[cur] = min(low[cur], dfn[to]);
        }
    }
    if (dfn[cur] == low[cur]) {
        ++ tot;
        int t;
        do {
            t = s.top();
            s.pop();
            in_stack[t] = false;
            scc[t] = tot;
        } while (t != cur);
    }
}

int main () {
    memset(head, -1, sizeof(head));
    cin >> n;
    for (int i = 1, v; i <= n; ++ i) {
        while (cin >> v && v) {
            add_edge(i, v);
            rec.push_back({ i, v });
        }
    }
    
    for (int i = 1; i <= n; ++ i)
        if (dfn[i] == 0)
            tarjan(i);
    for (int i = 0; i < rec.size(); ++ i) {
        int u = rec[i].u, v = rec[i].v;
        if (scc[u] == scc[v]) continue;
        ++ out_deg[scc[u]];
        ++ in_deg[scc[v]];
    }
    int x = 0, y = 0;
    for (int i = 1; i <= tot; ++ i) {
        x += (in_deg[i] == 0);
        y += (out_deg[i] == 0);
    }
    cout << x << endl;
    cout << (tot == 1 ? 0 : max(x, y)) << endl;
    return 0;
}
最后修改于: