这题真不爽,各种WA,写个题解浏览器还挂了,真不爽。
所以不多说了,就说关于判断是否是父节点的问题,不能直接判,会有重边,这种情况只能用编号判,传进去入边的编号,(k^1) != fa,这样就可以了。
要注意的细节很多啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊!
上代码:
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <queue>
#include <stack>
#define N 1000100
using namespace std; int n, power[N];
int p[N] = {}, next[N*], v[N*], bnum = -;
long long f1[N][] = {}, f2[N][] = {}; void addbian(int x, int y)
{
bnum++; next[bnum] = p[x]; p[x] = bnum; v[bnum] = y;
bnum++; next[bnum] = p[y]; p[y] = bnum; v[bnum] = x;
} int root, ban;
int cannot;
bool vis[N] = {}; void dfs(int now, int fa)
{
int k = p[now];
while (k != -)
{
if ((k^) != fa && v[k] != ban)
{
if (vis[v[k]])
{
root = v[k];
ban = now;
cannot = k^;
}
else
{
vis[v[k]] = ;
dfs(v[k], k);
}
}
k = next[k];
}
} void makeans_root(int now, int fa)
{
int k = p[now];
if (now == ban)
{
while (k != -)
{
if ((k^) != fa && v[k] != root)
{
makeans_root(v[k], k);
f1[now][] += max(f1[v[k]][], f1[v[k]][]);
f1[now][] += f1[v[k]][];
}
k = next[k];
}
return;
}
f1[now][] = power[now];
while (k != -)
{
if ((k^) != fa && k != cannot)
{
makeans_root(v[k], k);
f1[now][] += max(f1[v[k]][], f1[v[k]][]);
f1[now][] += f1[v[k]][];
}
k = next[k];
}
return;
} void makeans_ban(int now, int fa)
{
int k = p[now];
if (now == ban)
{
f2[now][] = power[now];
while (k != -)
{
if ((k^) != fa && v[k] != root)
{
makeans_ban(v[k], k);
f2[now][] += max(f2[v[k]][], f2[v[k]][]);
f2[now][] += f2[v[k]][];
}
k = next[k];
}
return;
}
f2[now][] = power[now];
while (k != -)
{
if ((k^) != fa && k != cannot)
{
makeans_ban(v[k], k);
f2[now][] += max(f2[v[k]][], f2[v[k]][]);
f2[now][] += f2[v[k]][];
}
k = next[k];
}
return;
} int main()
{
scanf("%d", &n);
for (int i = ; i <= n; ++i) p[i] = -;
for (int i = ; i <= n; ++i)
{
int x; scanf("%d%d", &power[i], &x);
addbian(x, i);
}
long long ans = ;
for (int i = ; i <= n; ++i)
if (!vis[i])
{
root = -; ban = -;
vis[i] = ; dfs(i, -);
makeans_root(root, -);
makeans_ban(root, -);
long long zans = ;
zans = max(f1[root][], zans);
zans = max(zans, f1[root][]);
zans = max(f2[root][], zans);
ans += zans;
}
printf("%lld\n", ans);
}