思路
给出一种 的做法。
对每组数据的每个 ,使用二分答案 。
对每一个 ,令 。
判断 是否可达到,即判断在 上进行时是否可得到 。
对每一个 ,令 。
二分时可以维护 ,只会修改 次。
在 上建立与线段树类似的满二叉树,然后 dp。
令 表示进入 所表示的区间(设为 )时,若可得到 至少需要与区间外交换几次。
容易发现 。
若 有子节点,则 。
时间复杂度
对每组数据的每个 ,二分时每次判定,因为 dp 状态个数为 ,转移的复杂度为 ,则复杂度为 。
每次二分,维护 复杂度为 ,判断为 ,则复杂度为 。
所以总复杂度为 。
代码
#include<bits/stdc++.h>
using namespace std;
#define int long long
const int N=1050000;
int T,k,id[N],cnt[N],a[N],b[N];
bool check(int n){
for(int i=0;i<n;i++) a[i]=max(1-cnt[i],0ll),b[i]=max(0ll,cnt[i]-1);
while(n>1){
for(int i=0;i<(n>>1);i++){
a[i]=a[i<<1]+a[i<<1|1],b[i]=b[i<<1]+b[i<<1|1];
if(a[i]&&b[i]) a[i]--,b[i]--;
}
n>>=1;
}
return !a[0];
}
void solve(){
cin>>k;
for(int i=0,w;i<(1<<k);i++) cin>>w,id[w-1]=i;
for(int i=1;i<=k;i++){
for(int j=0;j<(1<<i);j++) cnt[j]=0;
int l=0,r=(1<<k)-1,mid;
while(l<r){
mid=(l+r+1)>>1;
for(int j=mid;j<=r;j++) cnt[id[j]>>(k-i)]++;
if(check(1<<i)){
l=mid;
for(int j=mid;j<=r;j++) cnt[id[j]>>(k-i)]--;
}
else r=mid-1;
}
cout<<r+1<<' ';
}
cout<<'\n';
}
signed main(){
#ifndef ONLINE_JUDGE
freopen("test.in","r",stdin);
freopen("test.out","w",stdout);
#endif
ios::sync_with_stdio(false),cin.tie(0),cout.tie(0);
cin>>T;
while(T--) solve();
return 0;
}