一个很自然的思路,好像和官解不一样。
尝试刻画成子任务。
首先,对于一棵树,可以用 次操作,因为根节点的编号固定,所以我们在让左子树字典序尽量小的前提下右子树字典序尽量小,且可以交换左右子树(这相当于前序,中序,后序遍历的求解都是一个道理)。
那我们可以分两种情况,交换和不交换。
设这棵树的根为 ,这个任务为 。
那我们可以用递归到 和 。
如果 的字典序比 小,那我们可以直接去不交换了,否则就交换。
然后如果有剩下的操作次数,就可以留给另外一棵子树。
这样时间复杂度 ,过不去。
可以尝试去发现一些性质优化,考虑什么时候操作完一个子树会有剩下的操作次数。
设把 这棵树不考虑 ,所能操作到字典序最小的操作次数为 。
可以在最开始把 和对应的遍历序列预处理出来。
发现是 大于 时, 会留给另外一棵子树。
但是 大于 时,我们可以直接取出遍历序列解决交换后的左子树。
所以要么不用递归第三次,要么可以 解决一次递归。
于是时间复杂度就变成了 ,空间复杂度 。
做完了,详细实现的注释写代码里了。
#include<bits/stdc++.h>
using namespace std;
#define int long long
char ch;
int n,rt,k,l[400010],r[400010],cnt[400010];
vector<int>S[400010];
inline pair<vector<int>,int> dfs(int x,int k,int n){
vector<int>T_T;
if(k<0){T_T.push_back(2e9);return {T_T,2e9};}//k 都被减成负数了,直接 return
if(n==1){T_T.push_back(x);return {T_T,0};}//叶子节点
if(k>=cnt[x]) return {S[x],cnt[x]};//可以直接返回的情况
pair<vector<int>,int>L=dfs(l[x],k,(n+1)/2-1),R=dfs(r[x],k-1,(n+1)/2-1);//向两边递归
if(L.first<R.first){
pair<vector<int>,int>T=dfs(r[x],k-L.second,(n+1)/2-1);//如果 k>=L.second,说明上面 L 的递归是会直接返回的
vector<int>ans;
if(ch=='A') ans.push_back(x);//判断前中后序
ans.insert(ans.end(),L.first.begin(),L.first.end());
if(ch=='B') ans.push_back(x);
ans.insert(ans.end(),T.first.begin(),T.first.end());
if(ch=='C') ans.push_back(x);
return {ans,L.second+T.second};
}
else{//这里同理
pair<vector<int>,int>T=dfs(l[x],k-1-R.second,(n+1)/2-1);
vector<int>ans;
if(ch=='A') ans.push_back(x);
ans.insert(ans.end(),R.first.begin(),R.first.end());
if(ch=='B') ans.push_back(x);
ans.insert(ans.end(),T.first.begin(),T.first.end());
if(ch=='C') ans.push_back(x);
return {ans,R.second+T.second+1};
}
}
inline vector<int> DFS(int x,int n){
if(n==1){
vector<int>t;
t.push_back(x);
return S[x]=t;
}
vector<int>L=DFS(l[x],(n+1)/2-1),R=DFS(r[x],(n+1)/2-1);//递归两边
if(L<R){//哪边小我们直接交换
cnt[x]=cnt[l[x]]+cnt[r[x]];
vector<int>ans;
if(ch=='A') ans.push_back(x);
ans.insert(ans.end(),L.begin(),L.end());
if(ch=='B') ans.push_back(x);
ans.insert(ans.end(),R.begin(),R.end());
if(ch=='C') ans.push_back(x);
return S[x]=ans;
}
else{
cnt[x]=cnt[l[x]]+cnt[r[x]]+1;
vector<int>ans;
if(ch=='A') ans.push_back(x);
ans.insert(ans.end(),R.begin(),R.end());
if(ch=='B') ans.push_back(x);
ans.insert(ans.end(),L.begin(),L.end());
if(ch=='C') ans.push_back(x);
return S[x]=ans;
}
}
signed main() {
ios::sync_with_stdio(0);
cin.tie(0),cout.tie(0);
cin>>ch>>n>>rt>>k;
for(int i=1;i<=n;i++) cin>>l[i]>>r[i];
DFS(rt,n);//预处理
vector<int>ans=dfs(rt,k,n).first;
for(int i=0;i<ans.size();i++) cout<<ans[i]<<" ";
return 0;
}