题目
题意
hin好懂的题面。要注意一开始不会吃海狸。
思路
一开始想到了最优化子树,但忘了昨天前一题做的将子树答案排序进行最优化选取,看了题解才想起,看来举一反三的能力还不够。
那么定义 d p [ i ] dp[i] dp[i] 为以 i i i 为根子树的答案, L e f t [ i ] Left[i] Left[i] 为 i i i 号节点最优化选取子树后还剩的海狸数, S o n [ i ] Son[i] Son[i] 为 i i i 的每个子节点最优选取后,总共有多少个子节点可以与它来回走。
转移就很简单了,搜完每个儿子后,将儿子的 d p dp dp 放入 v e c t o r vector vector 中排序。然后如果能选,选取最大的几个, d p [ i ] + = v e c t o r [ j ] dp[i]\ += vector[j] dp[i] +=vector[j], L e t f [ i ] − − Letf[i]-- Letf[i]−−。若做完后 L e t f [ i ] Letf[i] Letf[i] 还有值,那么这个时候 S o n [ i ] Son[i] Son[i] 就派上用场了——即在 i i i 号节点和它的儿子之间来回走,表现为 d p [ i ] + = M i n ( L e f t [ i ] , S o n [ i ] ) ∗ 2 , L e f t [ i ] − = M i n ( L e f t [ i ] , S o n [ i ] ) dp[i]\ +=Min(Left[i],Son[i])*2,Left[i]-=Min(Left[i],Son[i]) dp[i] +=Min(Left[i],Son[i])∗2,Left[i]−=Min(Left[i],Son[i])。
Code
struct node
{
LL v, w;
node(){}
node(LL V,LL W)
{
v = V;
w = W;
}
};
LL k[MAXN], S;
vector<LL> G[MAXN];
bool cmp(LL x,LL y)
{
return x > y;
}
LL dp[MAXN], Left[MAXN], Son[MAXN];
void Dfs(LL x,LL Fa)
{
int l = G[x].size();
if (x == S)
Left[x] = k[x];
else Left[x] = k[x] - 1;
if (! l)
return ;
vector<LL> Temp;
for (Int i = 0; i < l; ++ i)
{
LL to = G[x][i];
if (to == Fa)
continue;
Dfs(to, x);
Son[x] += Left[to];
Temp.push_back( dp[to] );
}
sort(Temp.begin(), Temp.end(), cmp);
l = Temp.size();
for (Int i = 0; i < l && Left[x]; ++ i, Left[x] --)
dp[x] += Temp[i] + 2;
dp[x] += Min(Left[x], Son[x]) * 2;
Left[x] -= Min(Left[x], Son[x]);
return ;
}
int main()
{
LL n;
read( n );
for (Int i = 1; i <= n; ++ i)
read( k[i] );
for (Int i = 1; i < n; ++ i)
{
LL u, v;
read( u ); read( v );
G[u].push_back( v );
G[v].push_back( u );
}
read( S );
Dfs(S, S);
printf("%lld", dp[S]);
return 0 ;
}