1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| #include <iostream> using namespace std; using LL = long long; using PII = pair<int, int>; const int N = 1000002, M = N * 2; int n, c, p[N]; PII root[N / 2]; int h[N], w[N], e[M], ne[M], idx; LL f[N][2], ans; int find(int x) { return x == p[x] ? x : p[x] = find(p[x]); } void add(int u, int v) { e[++idx] = v, ne[idx] = h[u], h[u] = idx; } LL dp(int u, int fa) { f[u][0] = 0, f[u][1] = w[u]; for (int i = h[u]; i; i = ne[i]) { int v = e[i]; if (v == fa) continue; dp(v, u); f[u][0] += max(f[v][0], f[v][1]); f[u][1] += f[v][0]; } return f[u][0]; } int main() { scanf("%d", &n); for (int i = 1; i <= n; ++i) p[i] = i; for (int u = 1, v; u <= n; ++u) { scanf("%d%d", &w[u], &v); if (find(u) != find(v)) { p[find(u)] = find(v); add(u, v), add(v, u); } else { root[c++] = {u, v}; } } for (int i = 0; i < c; ++i) { auto [u, v] = root[i]; ans += max(dp(u, 0), dp(v, 0)); } printf("%lld\n", ans); return 0; }
|