首页 > 代码库 > [HNOI2002]营业额统计

[HNOI2002]营业额统计

题目链接:传送门

题目大意:中文题,略

题目思路:Splay模板题,找前驱和后继

#include <iostream>#include <cstdio>#include <cstdlib>#include <cmath>#include <algorithm>#include <cstring>#include <stack>#include <cctype>#include <queue>#include <string>#include <vector>#include <set>#include <map>#include <climits>#define lson rt<<1,l,mid#define rson rt<<1|1,mid+1,r#define fi first#define se second#define ping(x,y) ((x-y)*(x-y))#define mst(x,y) memset(x,y,sizeof(x))#define mcp(x,y) memcpy(x,y,sizeof(y))using namespace std;#define gamma 0.5772156649015328606065120#define MOD 1000000007#define inf 0x3f3f3f3f#define N 100005#define maxn 10typedef pair<int,int> PII;typedef long long LL;LL read(){    LL x=0,f=1;char ch=getchar();    while(ch<0||ch>9){if(ch==-)f=-1;ch=getchar();}    while(ch>=0&&ch<=9){x=(x<<3)+(x<<1)+ch-0;ch=getchar();}    return x*f;}int n,m,cnt,num,ans;struct Splay{    int rt,sz;     ///根节点,树节点总数    int va[N],son[N][2],fa[N];///值,左右儿子,父亲    void spin(int t){     ///旋转操作        int x=fa[t], f=fa[x], y=son[x][1]==t;        son[x][y]=son[t][y^1], fa[son[x][y]]=x;        son[t][y^1]=x, fa[x]=t, fa[t]=f;        if(f) son[f][son[f][1]==x]=t;    }    void play(int x){     /// splay操作        for(int i;i=fa[x];spin(x))            if(fa[i])            spin((x==son[i][0])==(i==son[fa[i]][0])?i:x);        rt=x;    }    void ins(int v){///插入元素        int y,x=rt;        while(1){            y=son[x][va[x]<v];            if(!y){                y=++sz, va[y]=v, fa[y]=x;                son[y][0]=son[y][1]=0;                son[x][va[x]<v]=y;                break;            }            x=y;        }play(y);    }    int suc(){    ///找后继        int x=rt,y=son[x][1];        while(son[y][0])y=son[y][0];        return va[y];    }    int pre(){    ///找前驱        int x=rt,y=son[x][0];        while(son[y][1])y=son[y][1];        return va[y];    }    void init(int x){  ///初始化,需要初始值        sz=rt=1;va[rt]=x;        fa[1]=son[1][0]=son[1][1]=0;    }}splay;int main(){    int i,j,group,x;    n=read();    if(scanf("%d",&x)==-1)x=0;    ans=x;    splay.init(inf);    splay.ins(-inf);    splay.ins(x);    for(i=2;i<=n;++i){        if(scanf("%d",&x)==-1)x=0;        splay.ins(x);        int t1=splay.pre(),t2=splay.suc();        ans+=min(x-t1,t2-x);    }    printf("%d\n",ans);    return 0;}

 

[HNOI2002]营业额统计