题解:P16534 [THUPC 2026 决赛] 年鉴整理
不妨归纳地构造,我们尝试按照从前往后的顺序将每个位置调整为最终状态的值。
不妨假设当前我们需要把位置
一个关键想法:既然我们关心这个变量,那么不妨直接考虑这个变量构成的序列。也就是令
注意到我们要求每次放到开头的
考虑构造一些基础操作。比如说我们连续操作两次位置
但是这个办法会在剩下的部分长度为
#include<bits/stdc++.h>
using namespace std;
vector<int> opt;
bool dfs(vector<int> h,int st){
if(st>(int)h.size()*(int)h.size()-(int)h.size()) return false;
bool flag=true;
for(int i=0;i+1<(int)h.size();i++){
if(h[i]>=h[i+1]) flag=false;
}
if(flag==true) return true;
for(int i=0;i+1<(int)h.size();i++){
swap(h[i],h[i+1]);
h[i]++;
opt.push_back(i);
if(dfs(h,st+1)==true) return true;
opt.pop_back();
h[i]--;
swap(h[i],h[i+1]);
}
return false;
}
const int maxn = 514+114;
vector<int> ans;
int n;
int a[maxn];
void solve(int now){
if(n-now+1<=4){
opt.clear();
vector<int> h;
for(int i=now;i<=n;i++) h.push_back(a[i]);
if(dfs(h,0)==false){
cout<<"-1\n";
return ;
}
for(int x:opt){
ans.push_back(x+now);
}
cout<<ans.size()<<"\n";
for(int x:ans) cout<<x<<" ";
cout<<"\n";
return ;
}
//找到 a[i]+i 最靠后的最小值
int ch=-1;
for(int i=now;i<=n;i++){
if(ch==-1||a[i]+i<=a[ch]+ch) ch=i;
}
//把 ch 移动到 now 上
while(ch>now){
ans.push_back(ch-1);
swap(a[ch-1],a[ch]);
a[ch-1]++;
ch--;
}
//把后面的整体 +1
for(int i=n;i>ch;i-=2){
if(i-1>ch){
ans.push_back(i-1);
ans.push_back(i-1);
a[i-1]++;
a[i]++;
}else{
ans.push_back(i);
swap(a[i],a[i+1]);
a[i]++;
}
}
solve(now+1);
}
int main(){
ios::sync_with_stdio(0);
cin.tie(0),cout.tie(0);
int t;
cin>>t;
while(t--){
cin>>n;
ans.clear();
for(int i=1;i<=n;i++) cin>>a[i];
solve(1);
}
return 0;
}