题意
题解
若要在节点
u
u
u 上放
W
u
W_u
Wu 梅花,则需遍历
u
u
u 的所有子节点
c
h
i
(
0
≤
i
<
n
u
m
)
ch_i(0\leq i<num)
chi(0≤i<num) 并放上梅花。那么需要从梅花岭带出的梅花数,即
R
e
s
u
Res_u
Resu,下界为
∑
0
≤
i
<
n
u
m
W
c
h
i
+
W
u
\sum_{0\leq i<num}W_{ch_i}+W_u
0≤i<num∑Wchi+Wu 假设按照
i
∈
[
0
,
n
u
m
)
i\in[0,num)
i∈[0,num) 的次序遍历以子节点
c
h
i
ch_i
chi 为根的子树,那么已经遍历的子节点上需要留下相应的梅花,其余节点可以回收。那么从遍历第
i
i
i 棵子树到第
i
i
i 个子节点放置完成梅花,整个过程中需要的最多梅花数为
∑
0
≤
j
<
i
W
c
h
j
+
R
e
s
c
h
i
\sum_{0\leq j<i}W_{ch_j}+Res_{ch_i}
0≤j<i∑Wchj+Reschi 那么得到
R
e
s
u
=
max
{
∑
0
≤
i
<
n
u
m
W
c
h
i
+
W
u
,
max
0
≤
i
<
n
u
m
{
∑
0
≤
j
<
i
W
c
h
j
+
R
e
s
c
h
i
}
}
Res_u=\max\bigg\{\sum_{0\leq i<num}W_{ch_i}+W_u,\max_{0\leq i<num}\{\sum_{0\leq j<i}W_{ch_j}+Res_{ch_i}\}\bigg\}
Resu=max{0≤i<num∑Wchi+Wu,0≤i<nummax{0≤j<i∑Wchj+Reschi}} 目标为求解一个子节点遍历顺序,使上式最优。考虑邻项交换。设
∑
0
≤
j
<
i
W
c
h
j
\sum_{0\leq j<i}W_{ch_j}
∑0≤j<iWchj 若满足下式,则交换后可能导致答案更差
max
{
s
+
R
e
s
c
h
i
,
s
+
W
c
h
i
+
R
e
s
c
h
i
+
1
}
<
max
{
s
+
R
e
s
c
h
i
+
1
,
s
+
W
c
h
i
+
1
+
R
e
s
c
h
i
}
\max\{s+Res_{ch_i},s+W_{ch_i}+Res_{ch_{i+1}}\}<\max\{s+Res_{ch_{i+1}},s+W_{ch_{i+1}}+Res_{ch_i}\}
max{s+Reschi,s+Wchi+Reschi+1}<max{s+Reschi+1,s+Wchi+1+Reschi} 变形简化后容易得到
W
c
h
i
−
R
e
s
c
h
i
<
W
c
h
i
+
1
−
R
e
s
c
h
i
+
1
W_{ch_i}-Res_{ch_i}<W_{ch_{i+1}}-Res_{ch_{i+1}}
Wchi−Reschi<Wchi+1−Reschi+1 排序后模拟即可。递归求解
R
e
s
Res
Res,总时间复杂度
O
(
N
log
N
)
O(N\log N)
O(NlogN)。
#include <bits/stdc++.h>
using namespace std;
const int maxn = 100010;
struct node
{
int r, w;
bool operator<(const node &o) const { return w - r < o.w - o.r; }
} ns[maxn];
int N, W[maxn], Res[maxn];
vector<int> G[maxn];
void dfs(int u)
{
int res = W[u], num = G[u].size();
for (int i = 0, v; i < num; ++i)
v = G[u][i], dfs(v), res += W[v];
for (int i = 0, v; i < num; ++i)
v = G[u][i], ns[i].r = Res[v], ns[i].w = W[v];
sort(ns, ns + num);
int sum = 0;
for (int i = 0; i < num; ++i)
res = max(res, sum + ns[i].r), sum += ns[i].w;
Res[u] = res;
}
int main()
{
ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
cin >> N;
for (int i = 1, p; i < N; ++i)
cin >> p, G[p - 1].push_back(i);
for (int i = 0; i < N; ++i)
cin >> W[i];
dfs(0);
for (int i = 0; i < N; ++i)
cout << Res[i] << (i == N - 1 ? '\n' : ' ');
return 0;
}