1 条题解
-
0
校园网(Network of Schools) 题解
思路分析
按题目要求使用对应数据结构与算法模拟/递推求解,注意数据范围边界与时间复杂度。
参考代码
#include <iostream> #include <vector> #include <algorithm> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int n; if (!(cin >> n)) return 0; vector<vector<int>> adj(n + 1); for (int i = 1; i <= n; ++i) { int x; while (cin >> x && x != 0) { adj[i].push_back(x); } } vector<int> dfn(n + 1, 0), low(n + 1, 0), in_stk(n + 1, 0), scc(n + 1, 0); vector<int> stk, call_u, call_idx; int timer = 0, scc_cnt = 0; for (int i = 1; i <= n; ++i) { if (!dfn[i]) { call_u.push_back(i); call_idx.push_back(0); dfn[i] = low[i] = ++timer; stk.push_back(i); in_stk[i] = 1; while (!call_u.empty()) { int u = call_u.back(); int& idx = call_idx.back(); if (idx < (int)adj[u].size()) { int v = adj[u][idx++]; if (!dfn[v]) { dfn[v] = low[v] = ++timer; stk.push_back(v); in_stk[v] = 1; call_u.push_back(v); call_idx.push_back(0); } else if (in_stk[v]) { low[u] = min(low[u], dfn[v]); } } else { if (low[u] == dfn[u]) { ++scc_cnt; while (true) { int x = stk.back(); stk.pop_back(); in_stk[x] = 0; scc[x] = scc_cnt; if (x == u) break; } } call_u.pop_back(); call_idx.pop_back(); if (!call_u.empty()) { low[call_u.back()] = min(low[call_u.back()], low[u]); } } } } } vector<int> indeg(scc_cnt + 1, 0), outdeg(scc_cnt + 1, 0); for (int u = 1; u <= n; ++u) { for (int v : adj[u]) { if (scc[u] != scc[v]) { outdeg[scc[u]]++; indeg[scc[v]]++; } } } int in0 = 0, out0 = 0; for (int i = 1; i <= scc_cnt; ++i) { if (indeg[i] == 0) in0++; if (outdeg[i] == 0) out0++; } cout << in0 << "\n"; cout << (scc_cnt == 1 ? 0 : max(in0, out0)) << "\n"; return 0; }
- 1
信息
- ID
- 8756
- 时间
- 1000ms
- 内存
- 256MiB
- 难度
- (无)
- 标签
- 递交数
- 0
- 已通过
- 0
- 上传者