题解:P15030 [UOI 2021 II Stage] A 先生的魔法球
看到要求字典序,那么一定是贪心选最值了。题目要求的是倒序选择,但是我们可以发现不能贪心选最大的作为最后面,因为我们每次必然选择一组数,而有些最大值是和最小值捆绑在一起的。
比如看一组样例:
4 4
1 5 3 2
如果贪心选择最大的在最后,由于每一次必定要选择两个数,所以第一个选
而最小序列是
正难则反,我们考虑假如第一次选择选第
所以可得一次在区间
注意在这里
考虑
其中每一次查找最小值都是在给定区间内查找最小值,可以用 st 表,线段树或树状数组维护,时间
但是还是不够,我们发现,对于一个区间,他现在能取得最小是固定且唯一的,所以我们考虑用优先队列存储每一个区间,比较的标准就是最小值大小,这样可以做到
代码:
#include<bits/stdc++.h>
using namespace std;
struct node{
int l,r,w;
bool operator < (node a) const{
return w>a.w;
}
};
priority_queue<node> q;
int n,k,lg2[1000007],st[2][1000007][27],mp[1000007];
//mp是某一个数的位置,便于确定最小值之后的最小是什么
vector<int> ans;
int ask(int op,int l,int r){//返回区间奇偶性为op的最小值
int len=lg2[r-l+1];
return min(st[op][l][len],st[op][r-(1<<len)+1][len]);
}
void pushq(int l,int r){//向队列中插入一个区间
if(r<=l) return;
int len=lg2[r-l+1];
//注意:这里的mp[mi]不能取到r
int mi=ask(l&1,l,r-1);
q.push({l,r,mi});
}
pair<int,int> qrery(int l,int r){//计算一个区间的贡献,即最小-次小对
int len=lg2[r-l+1];
//注意:这里的mp[mi]不能取到r
int mi=ask(l&1,l,r-1),cmi=ask((mp[mi]+1)%2,mp[mi]+1,r);
return {mi,cmi};
}
signed main(){
ios::sync_with_stdio(0);
cin.tie(0);
cin>>n>>k;
//st表计算
lg2[0]=0;
lg2[1]=0;
lg2[2]=1;
for(int i=3;i<=n;i++){
lg2[i]=lg2[i/2]+1;
}
memset(st,0x3f,sizeof(st));
for(int i=1;i<=n;i++){
cin>>st[i%2][i][0];
mp[st[i%2][i][0]]=i;
}
for(int j=1;j<=lg2[n]+1;j++){
for(int i=1;i+(1<<j)-1<=n;i++){
st[1][i][j]=min(st[1][i][j-1],st[1][i+(1<<(j-1))][j-1]);
st[0][i][j]=min(st[0][i][j-1],st[0][i+(1<<(j-1))][j-1]);
}
}
pushq(1,n);
while(!q.empty()){
int l=q.top().l,r=q.top().r;
q.pop();
pair<int,int> now=qrery(l,r);
//插入三段区间
pushq(l,mp[now.first]-1);
pushq(mp[now.first]+1,mp[now.second]-1);
pushq(mp[now.second]+1,r);
ans.push_back(now.first);
ans.push_back(now.second);
}
for(int i=0;i<k;i++){
cout<<ans[i]<<" ";
}
return 0;
}