Splay树模版

来源:互联网 发布:arp查看mac地址 编辑:程序博客网 时间:2024/05/21 21:50
#include <cstdio>#include <cstring>#include <algorithm>#include <cstdlib>using namespace std;typedef long long LL;const int maxn = 1000010;int pre[maxn], ch[maxn][2], sz[maxn];int root, top1; int val[maxn];  void rotate(int x, int d){    int y = pre[x];    ch[y][d^1] = ch[x][d];    pre[ch[x][d]] = y;    if(pre[y])        ch[pre[y]][ch[pre[y]][1] == y] = x;    pre[x] = pre[y];    ch[x][d] = y;    pre[y] = x;     } void Splay(int x, int goal){    while(pre[x] != goal)    {        if(pre[pre[x]] == goal)        {            rotate(x, ch[pre[x]][0] == x);        }        else        {            int y = pre[x], z = pre[y];            int d = (ch[z][0] == y);            if(ch[y][d] == x)            {                rotate(x, d^1);                rotate(x, d);            }            else            {                rotate(y, d);                rotate(x, d);            }        }    }    if(goal == 0)        root = x;} void NewNode(int &x, int f, int c){         x = ++top1;    ch[x][0] = ch[x][1];    //sz[x] = 1;    pre[x] = f;         val[x] = c;    //add[x] = 0;} void insert(int k){    int x = root;    if(x == 0)    {        NewNode(root, 0, k);        return;    }    while(ch[x][k>val[x]])        x = ch[x][k>val[x]];    NewNode(ch[x][k>val[x]], x, k);    Splay(ch[x][k>val[x]], 0);}int find1(int x){    while(ch[x][0])        x = ch[x][0];    return x;} int find2(int x){    while(ch[x][1])        x = ch[x][1];    return x;} int main(){    int n;    scanf("%d", &n);    int ans = 0;    for(int i = 1; i <= n; i++)    {        int x;        if(scanf("%d", &x) == EOF)            x = 0;          insert(x);         if(i == 1)        {            ans += x;        }        else        {            int temp = 0x3f3f3f3f;            if(ch[root][0])                temp = min(x-val[find2(ch[root][0])], temp);            if(ch[root][1])                temp = min(val[find1(ch[root][1])]-x, temp);            ans += temp;        }           }    printf("%d\n", ans);    return 0;}
0 0
原创粉丝点击