[HNOI2002]营业额统计 【splay无初始数组,单点插入找最值】

来源:互联网 发布:淘宝付款界面打不开 ie 编辑:程序博客网 时间:2024/06/05 04:16

Description

营业额统计 Tiger最近被公司升任为营业部经理,他上任后接受公司交给的第一项任务便是统计并分析公司成立以来的营业情况。 Tiger拿出了公司的账本,账本上记录了公司成立以来每天的营业额。分析营业情况是一项相当复杂的工作。由于节假日,大减价或者是其他情况的时候,营业额会出现一定的波动,当然一定的波动是能够接受的,但是在某些时候营业额突变得很高或是很低,这就证明公司此时的经营状况出现了问题。经济管理学上定义了一种最小波动值来衡量这种情况:该天的最小波动值 当最小波动值越大时,就说明营业情况越不稳定。 而分析整个公司的从成立到现在营业情况是否稳定,只需要把每一天的最小波动值加起来就可以了。你的任务就是编写一个程序帮助Tiger来计算这一个值。第一天的最小波动值为第一天的营业额。

Input

第一行为正整数 ,表示该公司从成立一直到现在的天数,接下来的n行每行有一个整数(有可能有负数),表示第i天公司的营业额。

Output

输出文件仅有一个正整数,即Sigma(每天最小的波动值)。结果小于2^31 。

Sample Input

6512546 

Sample Output

12

Hint

结果说明:5+|1-5|+|2-1|+|5-5|+|4-5|+|6-5|=5+4+1+0+1+1=12

此题数据有问题,详见讨论版http://www.lydsy.com/JudgeOnline/wttl/wttl.php?pid=1588


之前做的splay都是给定原始数组,在原始数组上修改单点值,这个题没有原始数组,其实都是一样的,多了一个insert函数而已,之前一直纠结于如何找出与最新插入数字最接近的数字,忘记了splay的最大特征:将操作的对象转到根节点并维护左小右大,所以说,插入新值之后左子树最大的和右子树最小的一定有一个离的最近!

#include <iostream>#include <stdio.h>#include <string.h>#include <algorithm>using namespace std;const int INF=0x3f3f3f3f;const int MAXN=1000010;int pre[MAXN],ch[MAXN][2],key[MAXN];int root,tot1;void NewNode(int &r,int father,int k){    r=++tot1;    pre[r]=father;    ch[r][0]=ch[r][1]=0;    key[r]=k;}void Init(){    root=tot1=0;    ch[root][0]=ch[root][1]=key[root]=pre[root]=0;}//旋转void Rotate(int x,int kind){    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调整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;}void Insert(int k){    int r=root;    if(r==0)    {        NewNode(root,0,k);///不是r是root 函数声明的时候是引用!!        return;    }    while(ch[r][key[r]<k])        r=ch[r][key[r]<k];    NewNode(ch[r][key[r]<k],r,k);    Splay(ch[r][key[r]<k],0);}int Get_Min(int r){    while(ch[r][0])    {        r=ch[r][0];    }    return r;}int Get_Max(int r){    while(ch[r][1])    {        r=ch[r][1];    }    return r;}int main(){    //freopen("cin.txt","r",stdin);    int n;    Init();    scanf("%d",&n);    int num;    int ans=0;    for(int i=1;i<=n;i++)    {        if(scanf("%d",&num)==EOF)num=0;        Insert(num);        if(i==1)        {            ans+=num;        }        else        {            int tmp=INF;            if(ch[root][0])                tmp=min(tmp,key[root]-key[Get_Max(ch[root][0])]);            if(ch[root][1])                tmp=min(tmp,key[Get_Min(ch[root][1])]-key[root]);            ans+=tmp;        }    }    printf("%d\n",ans);    return 0;}


0 0
原创粉丝点击