题目描述
给出n个数,求相邻两个数绝对值之差的最小值。有两种操作,一种是Q(表示你需要回答目前这些数的相邻两个数绝对值之差的最小值),一种是k(表示删原第K个数)。
数据范围
n,m(n,m<=100000)
n个数
以下每行一个共m个操作
样例输入
5 4
1 2 5 8 14
Q
K 2
K 3
Q
样例输出
1
6
解题思路
Splay,维护两个数之间的差的绝对值。
代码
#include <bits/stdc++.h>
#define Maxn 200005
using namespace std;
inline int Getint(){int x=0,f=1;char ch=getchar();while('0'>ch||ch>'9'){if(ch=='-')f=-1;ch=getchar();}while('0'<=ch&&ch<='9'){x=x*10+ch-'0';ch=getchar();}return x*f;}
inline int Getch(){char ch=getchar();while(ch!='Q'&&ch!='K')ch=getchar();return ch;}
struct splay{
int f[Maxn],son[Maxn][2],vl[Maxn],root,cnt;
void Rotate(int x){
int fa=f[x],gr=f[fa],s=son[fa][1]==x,sn=son[x][!s];
son[f[x]=gr][son[gr][1]==fa]=x;
son[f[fa]=x][!s]=fa;
son[f[sn]=fa][s]=sn;
}
void Splay(int x){
while(f[x]){
if(f[f[x]]&&(son[f[f[x]]][1]==f[x])==(son[f[x]][1]==x))Rotate(f[x]);
Rotate(x);
}
root=x;
}
void Insert(int val){
if(!root){root=++cnt;vl[cnt]=val;son[cnt][0]=son[cnt][1]=0;return;}
int p=root,L;
while(p){
L=p;
p=son[p][val>vl[p]];
}
p=L;
cnt++;
f[cnt]=p;
vl[cnt]=val;
son[p][val>vl[p]]=cnt;
Splay(cnt);
}
int Select(int val){
int p=root;
while(vl[p]!=val)p=son[p][val>vl[p]];
return p;
}
void Delete(int val){
int u=Select(val),p;
Splay(u);
if(!(son[u][0]*son[u][1])){
root=son[u][0]+son[u][1];
f[son[u][0]]=f[son[u][1]]=0;
son[u][0]=son[u][1]=0;
return;
}
int LL=son[u][0],rr=son[u][1];
p=LL;son[u][0]=son[u][1]=0;
f[p]=0;
while(son[p][1])p=son[p][1];
Splay(p);
son[p][1]=rr;
f[rr]=p;
}
int Ask(){
int p=root;
while(son[p][0])p=son[p][0];
return vl[p];
}
}Solver;
struct node{int pre,nxt,vl;}w[Maxn];
void Delete(int x){w[w[x].pre].nxt=w[x].nxt;w[w[x].nxt].pre=w[x].pre;w[x].nxt=w[x].pre=0;}
int main(){
int n=Getint(),m=Getint(),p=1;
for(int i=1;i<=n;i++){
w[i].vl=Getint();
w[i].pre=i-1;
w[i].nxt=(i+1<=n?i+1:0);
}
for(int i=1;i<n;i++)
Solver.Insert(abs(w[i].vl-w[i+1].vl));
while(m--){
char ch=Getch();
if(ch=='Q')cout<<Solver.Ask()<<"\n";
else{
int i=Getint();
if(w[i].pre)Solver.Delete(abs(w[i].vl-w[w[i].pre].vl));
if(w[i].nxt)Solver.Delete(abs(w[i].vl-w[w[i].nxt].vl));
if(w[i].pre&&w[i].nxt)Solver.Insert(abs(w[w[i].pre].vl-w[w[i].nxt].vl));
Delete(i);
}
}
return 0;
}