1 条题解
-
0
奶牛拜访(Visits S) 题解
思路分析
按题目要求使用对应数据结构与算法模拟/递推求解,注意数据范围边界与时间复杂度。
参考代码
#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<int> a(n + 1), indeg(n + 1, 0); vector<long long> v(n + 1); long long total = 0; for (int i = 1; i <= n; ++i) { cin >> a[i] >> v[i]; indeg[a[i]]++; total += v[i]; } vector<int> q; q.reserve(n); vector<int> rem(n + 1, 0); for (int i = 1; i <= n; ++i) { if (indeg[i] == 0) { q.push_back(i); rem[i] = 1; } } for (size_t head = 0; head < q.size(); ++head) { int u = q[head]; int nxt = a[u]; if (--indeg[nxt] == 0) { q.push_back(nxt); rem[nxt] = 1; } } for (int i = 1; i <= n; ++i) { if (!rem[i]) { long long mn = v[i]; int cur = i; while (!rem[cur]) { rem[cur] = 1; mn = min(mn, v[cur]); cur = a[cur]; } total -= mn; } } cout << total << "\n"; return 0; }
- 1
信息
- ID
- 8761
- 时间
- 1000ms
- 内存
- 256MiB
- 难度
- (无)
- 标签
- 递交数
- 0
- 已通过
- 0
- 上传者