洛谷P2341 受歡迎的牛
阿新 • • 發佈:2022-05-17
受歡迎的牛
縮點
USACO03FALL / HAOI2006] 受歡迎的牛 G - 洛谷 | 電腦科學教育新生態 (luogu.com.cn)
用 tarjan 縮點後,在每個強連通分量中的點都可以互相到達。
在 DAG 中
如果有大於 1 個出口,則兩個出口之間肯定不能相互到達,所以沒有明星
如果只有一個出口,則別的點一定可以到出口,所以這個出口的 SCC 中所有點都是明星
所以求完 SCC 後判斷每個強連通分量的出度即可
#include <iostream> #include <cstring> #include <algorithm> #include <vector> #include <cmath> #include <stack> using namespace std; typedef long long ll; const int N = 1e4 + 10; int n, m; vector<int> G[N]; int tin[N], tim; int scc_cnt, sz[N], id[N], low[N]; bool in_stk[N]; stack<int> stk; int dout[N]; void add(int a, int b) { G[a].push_back(b); } void tarjan(int u) { tin[u] = low[u] = ++tim; stk.push(u); in_stk[u] = true; for (int v : G[u]) { if (!tin[v]) { tarjan(v); low[u] = min(low[u], low[v]); } else if (in_stk[v]) low[u] = min(low[u], tin[v]); } if (tin[u] == low[u]) { ++scc_cnt; int y; do { y = stk.top(); stk.pop(); in_stk[y] = false; id[y] = scc_cnt; sz[scc_cnt]++; }while(y != u); } } int main() { ios::sync_with_stdio(false), cin.tie(0), cout.tie(0); cin >> n >> m; while(m--) { int a, b; cin >> a >> b; add(a, b); } for (int i = 1; i <= n; i++) if (!tin[i]) tarjan(i); for (int u = 1; u <= n; u++) { for (int v : G[u]) { if (id[u] != id[v]) dout[id[u]]++; } } int cnt = 0, sum = 0; for (int i = 1; i <= scc_cnt; i++) { if (dout[i] == 0) { cnt++; sum += sz[i]; if (cnt > 1) { sum = 0; break; } } } cout << sum << endl; return 0; }