题解:P16428 「YLLOI-R4-T4」稻香
SunXiheng1124 · · 题解
本题解采取树形动态规划。
前序只需要暴力模拟,主要解释一下中序和后序。注意到字典序由叶子节点顺序决定。
如果从根节点开始递归,那么越早的决策对答案影响越大,因此将操作数优先花在较高的位置上。所以,如果交换更优且还有操作数,那么一定交换。
什么时候交换更优?就是在操作数允许的情况下,如果字典序的第一位比不交换小了,那么就更优。由于不存在并列,所以只需要看第一位。考虑如何刻画这个约束。
定义
考虑交换一个节点
同时,注意到当
最后,我们尝试求
于是,这个值是可以做类似前缀和处理的:
则
所以其实并不需要计算
到此为止这个题就处理完了。代码:
/*
n<=2e5。
1
2 3
4 5 6 7
前序 1 2 4 5 3 6 7
中序 4 2 5 1 6 3 7
后序 4 5 2 6 7 3 1
前序:
最简单:递归的时候比较左右子节点大小,如果左侧的大于右侧的,那么交换。
中序/后序:由叶子节点顺序决定。
定义 f[u] 表示第一个到达(同一深度)一个点需要的交换次数,相当于走右子树的次数。
注意到 u-路径->v 的交换次数相当于 f[v]-f[u]。
令 g[u][i] f[leaf]-f[u]<=i 时 v 的最小值,数组大小 O(nlogn)。
设存在一条边 u-->v,则 g[u][i]=min(g[ch[u][0]][i],g[ch[u][1]][i-1],g[u][i-1])
然后从根节点开始,考虑交换子树:
定义状态 {u,left},令 t=h[u]。
则如果 g[ch[u][1]][t-1]<g[ch[u][0]][t](不存在平局的情况),那么当前点要交换,{u,cost}->{v,left-1}。
随着遍历存储操作后的树即可。
*/
#include<bits/stdc++.h>
using namespace std;
const int N=2e5+5,K=20;
int n,s,k,ch[N][2];
int f[N],g[N][K],h[N];
char c;
vector<int> ans;
int DFS1(int u,int x){
ans.push_back(u);
if(ch[u][0]==0&&ch[u][1]==0){
// 叶子
return x;
}
if(x>0&&ch[u][1]<ch[u][0]){
int t=DFS1(ch[u][1],x-1);
return DFS1(ch[u][0],t);
}
else{
int t=DFS1(ch[u][0],x);
return DFS1(ch[u][1],t);
}
}
void DFS2(int u){
// 预处理 f,g,h
if(ch[u][0]==0&&ch[u][1]==0){
// 叶子
for(int i=0;i<K;i++) g[u][i]=u;
return;
}
f[ch[u][0]]=f[u];
f[ch[u][1]]=f[u]+1;
DFS2(ch[u][0]);
DFS2(ch[u][1]);
h[u]=h[ch[u][0]]+1;
g[u][0]=g[ch[u][0]][0];
for(int i=1;i<K;i++){
g[u][i]=min({g[ch[u][0]][i],g[ch[u][1]][i-1],g[u][i-1]});
}
}
int DFS3(int u,int x){
if(ch[u][0]==0&&ch[u][1]==0) {ans.push_back(u);return x;}
int temp=min(x,h[u]);
if(temp>0&&g[ch[u][1]][temp-1]<g[ch[u][0]][temp]){
// 交换
if(c=='B'){
// 中序
int t=DFS3(ch[u][1],x-1);
ans.push_back(u);
return DFS3(ch[u][0],t);
}
else{
// 后序
int t=DFS3(ch[u][1],x-1);
t=DFS3(ch[u][0],t);
ans.push_back(u);
return t;
}
}
else{
// 不交换
if(c=='B'){
// 中序
int t=DFS3(ch[u][0],x);
ans.push_back(u);
return DFS3(ch[u][1],t);
}
else{
// 后序
int t=DFS3(ch[u][0],x);
t=DFS3(ch[u][1],t);
ans.push_back(u);
return t;
}
}
}
int main(){
memset(g,0x3f,sizeof(g));
scanf(" %c",&c);
scanf("%d%d%d",&n,&s,&k);
for(int i=1;i<=n;i++) scanf("%d%d",&ch[i][0],&ch[i][1]);
if(c=='A') DFS1(s,k);
else {DFS2(s);DFS3(s,k);}
for(auto u:ans) printf("%d ",u);
return 0;
}