POJ 1236 Network of Schools
阿新 • • 發佈:2020-10-31
傳送門
同 AcWing 367 學校網路、洛谷 P2812 校園網路 加強版
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #include <stack> using namespace std; typedef long long ll; typedef pair<int, int> p; const int maxn(1e4 + 10); const int maxm(5e6 + 10); int ecnt, head[maxn]; int tim, dfn[maxn], low[maxn]; int scnt, scc[maxn], siz[maxn]; int indeg[maxn], outdeg[maxn]; bool vis[maxn]; stack<int> st; struct edge { int to, nxt; } edges[maxm]; template<typename T> inline const T read() { T x = 0, f = 1; char ch = getchar(); while (ch < '0' || ch > '9') { if (ch == '-') f = -1; ch = getchar(); } while (ch >= '0' && ch <= '9') { x = (x << 3) + (x << 1) + ch - '0'; ch = getchar(); } return x * f; } template<typename T> inline void write(T x, bool ln) { if (x < 0) { putchar('-'); x = -x; } if (x > 9) write(x / 10, false); putchar(x % 10 + '0'); if (ln) putchar(10); } void addEdge(int u, int v) { edges[ecnt].to = v; edges[ecnt].nxt = head[u]; head[u] = ecnt++; } void tarjan(int u) { dfn[u] = low[u] = ++tim; vis[u] = true; st.push(u); for (int i = head[u]; compl i; i = edges[i].nxt) { int v = edges[i].to; if (not dfn[v]) { tarjan(v); low[u] = min(low[u], low[v]); } else if (vis[v]) { low[u] = min(low[u], dfn[v]); } } if (dfn[u] == low[u]) { ++scnt; int v = 0; do { v = st.top(); st.pop(); vis[v] = false; scc[v] = scnt; ++siz[scnt]; } while (v not_eq u); } } int main() { #ifdef ONLINE_JUDGE #else freopen("input.txt", "r", stdin); #endif ios::sync_with_stdio(false); memset(head, -1, sizeof head); int n = read<int>(); for (int u = 1; u <= n; ++u) { int v = 0; while ((v = read<int>())) { addEdge(u, v); } } for (int i = 1; i <= n; ++i) { if (not dfn[i]) { tarjan(i); } } for (int u = 1; u <= n; ++u) { for (int i = head[u]; compl i; i = edges[i].nxt) { int v = edges[i].to; int a = scc[u], b = scc[v]; if (a not_eq b) { ++indeg[b]; ++outdeg[a]; } } } int hcnt = 0, tcnt = 0; for (int i = 1; i <= scnt; ++i) { if (not indeg[i]) { ++hcnt; } if (not outdeg[i]) { ++tcnt; } } write(hcnt, true); write(scnt > 1 ? max(hcnt, tcnt) : 0, true); return 0; }