题解
[USACO06DEC] Cow Picnic S
1 条题解
-
0
1. 解题思路
从每头奶牛所在牧场分别搜索,累计每个牧场被多少次搜索到,次数等于奶牛数的牧场即公共可达地点。
2. 坑点和注意事项
K≤100、N≤1000、M≤10000。有向边不能反走,同一牧场多头牛也需分别计数;每轮重新标记避免有环重复访问。
3. 复杂度
- 时间复杂度:O(K(N+M))。
- 空间复杂度:O(N+M)。
/* 思路:从每头奶牛所在牧场分别搜索,累计每个牧场被多少次搜索到,次数等于奶牛数的牧场即公共可达地点。 关键规则与坑点:K≤100、N≤1000、M≤10000。有向边不能反走,同一牧场多头牛也需分别计数;每轮重新标记避免有环重复访问。 时间复杂度:O(K(N+M))。空间复杂度:O(N+M)。 */ #include <bits/stdc++.h> using namespace std; int h[1005], to[10005], nxt[10005], c[105], cnt[1005]; int main() { int k, n, m; cin >> k >> n >> m; for (int i = 0; i < k; i++) cin >> c[i]; fill(h, h + n + 1, -1); for (int i = 0; i < m; i++) { int a, b; cin >> a >> b; to[i] = b; nxt[i] = h[a]; h[a] = i; } for (int z = 0; z < k; z++) { bool seen[1005] = {}; stack<int> s; s.push(c[z]); seen[c[z]] = true; while (!s.empty()) { int u = s.top(); s.pop(); cnt[u]++; for (int i = h[u]; i != -1; i = nxt[i]) { int v = to[i]; if (!seen[v]) { seen[v] = true; s.push(v); } } } } int ans = 0; for (int i = 1; i <= n; i++) ans += cnt[i] == k; cout << ans << endl; }
- 1