洛谷 P3165 [CQOI2014]排序机械臂 【无旋treap、Splay】
·
题目链接
题意:
给出一个数组,找到并输出第 i i i 小的数的位置 P P P,然后翻转区间 [ i , P ] [i,P] [i,P] ,重复 n n n 次,即最后数组的非降序的
题解:
每次反转一个区间同时要快速找到最小数的位置,有点像文艺平衡树,可以用treap或者Splay实现,Splay暂时还不会,下次来补
treap:
#include<iostream>
#include<sstream>
#include<string>
#include<queue>
#include<map>
#include<unordered_map>
#include<set>
#include<vector>
#include<stack>
#include <utility>
#include<algorithm>
#include<cstdio>
#include<list>
#include<cmath>
#include<cstdlib>
#include<cstring>
#include<iomanip>
#include<time.h>
#include<random>
using namespace std;
#include<ext/pb_ds/priority_queue.hpp>
#include<ext/pb_ds/tree_policy.hpp>
#include<ext/pb_ds/assoc_container.hpp>
#include<ext/pb_ds/assoc_container.hpp>
#include<ext/pb_ds/hash_policy.hpp>
using namespace __gnu_pbds;
#include<ext/rope>
using namespace __gnu_cxx;
#define int long long
#define PI acos(-1.0)
#define eps 1e-9
#define lowbit(a) ((a)&-(a))
const int mod = 1e9+7;
int qpow(int a,int b){
int ans=1;
while(b){
if(b&1)ans=(ans*a)%mod;
a=(a*a)%mod;
b>>=1;
}
return ans;
}
const int INF = 0x3f3f3f3f;
const int N = 1e6+10;
struct arr{
int num,id;
}a[N];
bool cmp(arr a,arr b){
if(a.num==b.num)return a.id<b.id;
return a.num<b.num;
}
mt19937 rng(233);
struct node{
int l,r;
int key,val,lst,tag,sz;
}fhq[N];
int tot,rt,x,y,z,n,tmp[N];
int newnode(int val){
fhq[++tot].val=val,fhq[tot].key=rng(),fhq[tot].sz=1,fhq[tot].lst=val;
return tot;
}
void update(int now){
fhq[now].sz=fhq[fhq[now].l].sz+fhq[fhq[now].r].sz+1;
fhq[now].lst=fhq[now].val;
if(fhq[now].l)fhq[now].lst=min(fhq[now].lst,fhq[fhq[now].l].lst);
if(fhq[now].r)fhq[now].lst=min(fhq[now].lst,fhq[fhq[now].r].lst);
}
void pd(int now){
swap(fhq[now].l,fhq[now].r);
if(fhq[now].l)fhq[fhq[now].l].tag^=1;
if(fhq[now].r)fhq[fhq[now].r].tag^=1;
fhq[now].tag=0;
}
void split(int now,int val,int &x,int &y){
if(!now)x=y=0;
else{
if(fhq[now].tag)pd(now);
if(fhq[fhq[now].l].sz<val){
x=now;
split(fhq[now].r,val-fhq[fhq[now].l].sz-1,fhq[now].r,y);
}
else{
y=now;
split(fhq[now].l,val,x,fhq[now].l);
}
update(now);
}
}
int merge(int x,int y){
if(!x||!y) return x+y;
if(fhq[x].key<fhq[y].key){
if(fhq[x].tag)pd(x);
fhq[x].r=merge(fhq[x].r,y);
update(x);
return x;
}
else{
if(fhq[y].tag)pd(y);
fhq[y].l=merge(x,fhq[y].l);
update(y);
return y;
}
}
int getrank(int now){
int ans=1;
while(1){
if(fhq[now].tag)pd(now);
if(fhq[now].l&&fhq[fhq[now].l].lst==fhq[now].lst)now=fhq[now].l;
else if(fhq[now].r&&fhq[fhq[now].r].lst==fhq[now].lst)ans+=fhq[fhq[now].l].sz+1,now=fhq[now].r;
else return ans+=fhq[fhq[now].l].sz;
}
}
//#define endl '\n'
signed main(){
std::ios::sync_with_stdio(false);
cin.tie(0),cout.tie(0);
cin>>n;
for(int i=1;i<=n;i++){
cin>>a[i].num; a[i].id=i;
}
sort(a+1,a+1+n,cmp);
for(int i=1;i<=n;i++)tmp[a[i].id]=i;
for(int i=1;i<=n;i++)rt=merge(rt,newnode(tmp[i]));
for(int i=1;i<=n;i++){
int k=getrank(rt);
split(rt,k,x,y); split(x,k-1,x,z);
fhq[x].tag^=1;
rt=merge(x,y);
cout<<k+i-1<<" ";
}
}
更多推荐
所有评论(0)