bzoj1588 splay模板

来源:互联网 发布:电脑编程c语言的软件 编辑:程序博客网 时间:2024/06/05 00:13
#include<stdio.h>#include<stdlib.h>#include<string.h>#include<math.h>#include<iostream>#include<algorithm>#include<stack>#include<queue>#include<vector>#include<set>#include<map>#include<string>using namespace std;typedef long long ll;typedef pair<int,int>P;const int INF=0x3f3f3f3f;const ll INFF=0x3f3f3f3f3f3f3f3f;const double pi=acos(-1.0);const double eps=1e-9;const int maxn=33333;int fa[maxn],ch[maxn][2],root,k[maxn],ind=1;void rotate(int p){    int q=fa[p],y=fa[q],x=ch[q][1]==p;    ch[q][x]=ch[p][x^1]; fa[ch[q][x]]=q;    ch[p][x^1]=q; fa[q]=p; fa[p]=y;    if(y)    {        if(ch[y][0]==q)            ch[y][0]=p;        else if(ch[y][1]==q)            ch[y][1]=p;    }}void splay(int x){    for(int y;y=fa[x];rotate(x))    {        if(fa[y])        {            rotate((x==ch[y][0])==(y==ch[fa[y]][0])?y:x);        }    }    root=x;}void insert(int x,int v){    int y;    while(1)    {        y=ch[x][k[x]<v];        if(!y)        {            y=++ind;            k[y]=v;            ch[y][0]=ch[y][1]=0;            fa[y]=x;            ch[x][k[x]<v]=y;            break;        }        x=y;    }    splay(y);}int pre(int x){    int tmp=ch[x][0];    while(ch[tmp][1])        tmp=ch[tmp][1];    return k[tmp];}int suc(int x){    int tmp=ch[x][1];    while(ch[tmp][0])        tmp=ch[tmp][0];    return k[tmp];}int main(){    int n,t,ans=0;    scanf("%d",&n);    if(scanf("%d",&t)==EOF) t=0;    root=1;k[root]=t;    ch[root][0]=ch[root][1]=0;    fa[root]=0;    ans=t;    insert(root,INF);    insert(root,-INF);    for(int i=2;i<=n;i++)    {        if(scanf("%d",&t)==EOF)t=0;        insert(root,t);        int a=pre(root);        int b=suc(root);        ans+=min(t-a,b-t);    }    printf("%d\n",ans);    return 0;}

原创粉丝点击