Description
营业额统计 Tiger最近被公司升任为营业部经理,他上任后接受公司交给的第一项任务便是统计并分析公司成立以来的营业情况。 Tiger拿出了公司的账本,账本上记录了公司成立以来每天的营业额。分析营业情况是一项相当复杂的工作。由于节假日,大减价或者是其他情况的时候,营业额会出现一定的波动,当然一定的波动是能够接受的,但是在某些时候营业额突变得很高或是很低,这就证明公司此时的经营状况出现了问题。经济管理学上定义了一种最小波动值来衡量这种情况: 该天的最小波动值 当最小波动值越大时,就说明营业情况越不稳定。 而分析整个公司的从成立到现在营业情况是否稳定,只需要把每一天的最小波动值加起来就可以了。你的任务就是编写一个程序帮助Tiger来计算这一个值。 第一天的最小波动值为第一天的营业额。
Input
第一行为正整数 ,表示该公司从成立一直到现在的天数,接下来的n行每行有一个整数(有可能有负数) ,表示第i天公司的营业额。
Output
输出文件仅有一个正整数,即Sigma(每天最小的波动值) 。结果小于2^31 。
Sample Input
6 5 1 2 5 4 6
Sample Output
12
Treap求得当前key值在树里的上界和下界,然后累加绝对值较小的。
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <algorithm>
#include <time.h>
using namespace std;
struct node
{
int size;
int rank;
int key;
node *son[2];
node(int key):key(key)
{
size=1;
rank=rand();
son[0]=son[1]=NULL;
}
bool operator < (const node &a)const
{
return rank<a.rank;
}
int cmp(int x)const
{
if(x==key) return -1;
return x<key?0:1;
}
void update()
{
size=1;
if(son[0]!=NULL) size+=son[0]->size;
if(son[1]!=NULL) size+=son[1]->size;
}
};
struct Treap
{
void rotate(node* &o,int d)
{
node *k=o->son[d^1];
o->son[d^1]=k->son[d];
k->son[d]=o;
o->update();
k->update();
o=k;
}
void build(node* &o,int x)
{
if(o==NULL)
o=new node(x);
else
{
int d=x<o->key?0:1;
build(o->son[d],x);
o->update();
if(o->rank<o->son[d]->rank)
rotate(o,d^1);
}
o->update();
}
void upperBound(node *o,int x,int &ans)
{
if(o==NULL) return;
if(o->key>=x)
{
ans=o->key;
upperBound(o->son[0],x,ans);
}
else upperBound(o->son[1],x,ans);
}
void lowerBound(node *o,int x,int &ans)
{
if(o==NULL) return;
if(o->key<=x)
{
ans=o->key;
lowerBound(o->son[1],x,ans);
}
else lowerBound(o->son[0],x,ans);
}
} treap;
int main()
{
int n,a,ans=0,x,y;
scanf("%d%d",&n,&a);
node *root=new node(a);
treap.build(root,a);
ans+=a;
for(int i=1; i<n; i++)
{
if(scanf("%d",&a)==EOF) a=0;
treap.lowerBound(root,a,x);
treap.upperBound(root,a,y);
ans+=min(abs(a-x),abs(a-y));
treap.build(root,a);
}
printf("%d\n",ans);
return 0;
}