首先我们看到这道题:
我的天啊, 这不是没有上司的舞会吗???
但是定眼一看, 我们找出了不同:
没有上司的舞会中:有一个顶头上司, 他是没有上司的
然而, 这道题, 每个人都有自己讨厌的人
显然, 前者是树, 那么后者则是在树上填了一条边, 构成了一个环。
那么这道题就很明显了, 明显的基环树。
我们用套路的思路: 拆边。
我们找到环, 将其中的两边拆掉, 随意判定一个点及其一个再环上的相邻节点即可。
代码如下:
#include<bits/stdc++.h>
using namespace std;
const int N = 2e6 + 10;
#define ll long long
int n, val[N]; ll ans, f[N][2];
struct __edge {
int to, nxt;
} edge[N];
int head[N], cnt, fa[N];
int root;
bool vis[N];
void add_edge(int u, int v) {
edge[++cnt].to = v;
edge[cnt].nxt = head[u];
head[u] = cnt;
}
void DP(int now) {
vis[now] = 1;
f[now][0] = 0;
f[now][1] = val[now];
for(int i = head[now]; i; i = edge[i].nxt) {
int to = edge[i].to;
if(to != root) {
DP(to);
f[now][0] += max(f[to][1], f[to][0]);
f[now][1] += f[to][0];
}
else
f[to][1] = INT_MIN;
}
}
inline void check(int x) {
vis[x] = 1, root = x;
while(!vis[fa[root]]) {
root = fa[root];
vis[root] = 1;
}
DP(root);
ll p = max(f[root][0], f[root][1]);
root=fa[root]; DP(root);
ans += max(p, max(f[root][0], f[root][1]));
return;
}
int main() {
scanf("%d", &n);
for(int i = 1; i <= n; i++) {
scanf("%d %d", &val[i], &fa[i]);
add_edge(fa[i], i);
}
for(int i = 1; i <= n; i++)
if(!vis[i])
check(i);
printf("%lld", ans);
return 0;
}