【SPLAY】 [HNOI2002] 营业额统计 模板

来源:互联网 发布:红蜘蛛软件安卓版 编辑:程序博客网 时间:2024/05/15 04:53

点击打开链接

模板

#include <stdio.h>#include <string.h>#include <stdlib.h>#include <math.h>#include <string>#include <iostream>#include <algorithm>using namespace std;#include <queue>#include <stack>#include <vector>#include <list>#include <deque>#include <set>#pragma comment(linker, "/STACK:1024000000,1024000000")#include <map>typedef long long LL;const int INF = 1<<29;const LL mod = 1e9+7;const int MAXN = 100050;struct SPLAY{    int pre[MAXN],key[MAXN],ch[MAXN][2],root,tol;    void init()    {        root=0,tol=0;    }    void NewNode(int &r,int father,int k)    {        r= ++tol;        pre[r]=father;        key[r]=k;        ch[r][0]=ch[r][1]=0;    }    void Rotate(int x,int kind)//0为左旋,1为右旋    {        int y=pre[x];        ch[y][!kind]=ch[x][kind];        pre[ch[x][kind]]=y;        if(pre[y])            ch[pre[y]][ch[pre[y]][1]==y]=x;        pre[x]=pre[y];        ch[x][kind]=y;        pre[y]=x;    }    //Splay调整,将根为r的子树调整为goal    void Splay(int r,int goal)    {        while(pre[r]!=goal)        {            if(pre[pre[r]]==goal)                Rotate(r,ch[pre[r]][0]==r);            else            {                int y=pre[r];                int kind=ch[pre[y]][0]==y;                if(ch[y][kind]==r)                {                    Rotate(r,!kind);                    Rotate(r,kind);                }                else                {                    Rotate(y,kind);                    Rotate(r,kind);                }            }        }        if(goal==0) root=r;    }    int Insert(int k)    {        int r=root;        while(ch[r][key[r]<k])        {            if(key[r]==k)//key不重复            {                Splay(r,0);                return 0;            }            r=ch[r][key[r]<k];        }        NewNode(ch[r][k>key[r]],r,k);        Splay(ch[r][k>key[r]],0);        return 1;    }    int get_pre(int x)    {        int tmp=ch[x][0];        if(tmp==0) return INF;        while(ch[tmp][1]) tmp=ch[tmp][1];        return key[x]-key[tmp];    }    int get_next(int x)    {        int tmp=ch[x][1];        if(tmp==0) return INF;        while(ch[tmp][0]) tmp=ch[tmp][0];        return key[tmp]-key[x];    }    }s;int main(){    int n;    while(scanf("%d",&n)!=EOF)    {        int ans=0,x;        s.init();        for(int i=1;i<=n;i++)        {            if(scanf("%d",&x)==EOF) x=0;            if(i==1){                s.NewNode(s.root,0,x);                ans=x;                continue;            }            if(s.Insert(x)==0) continue;            ans+=min(s.get_next(s.root),s.get_pre(s.root));        }        cout<<ans<<endl;    }    return 0;}


0 0
原创粉丝点击