1296 营业额统计
时间限制: 1 s 空间限制: 128000 KB 题目等级 : 大师 Master
题目描述 Description
Tiger最近被公司升任为营业部经理,他上任后接受公司交给的第一项任务便是统计并分析公司成立以来的营业情况。
Tiger拿出了公司的账本,账本上记录了公司成立以来每天的营业额。分析营业情况是一项相当复杂的工作。由于节假日,大减价或者是其他情况的时候,营业额会出现一定的波动,当然一定的波动是能够接受的,但是在某些时候营业额突变得很高或是很低,这就证明公司此时的经营状况出现了问题。经济管理学上定义了一种最小波动值来衡量这种情况:
该天的最小波动值 = min{|该天以前某一天的营业额-该天营业额|}
当最小波动值越大时,就说明营业情况越不稳定。
而分析整个公司的从成立到现在营业情况是否稳定,只需要把每一天的最小波动值加起来就可以了。你的任务就是编写一个程序帮助Tiger来计算这一个值。
第一天的最小波动值为第一天的营业额。
输入描述 Input Description
第一行为正整数n(n<=32767),表示该公司从成立一直到现在的天数,接下来的n行每行有一个正整数ai(ai<=1000000),表示第i天公司的营业额。
输出描述 Output Description
输出文件仅有一个正整数,即每天最小波动值之和,小于231
样例输入 Sample Input
6
5
1
2
5
4
6
样例输出 Sample Output
12
数据范围及提示 Data Size & Hint
结果说明:5+|1-5|+|2-1|+|5-5|+|4-5|+|6-5|=5+4+1+0+1+1=12
#include<iostream>
#include<cstring>
#include<cstdio>
#include<cmath>
using namespace std;
#define maxn 32780
#define INF 2000000
int ans=0,root;
struct Spaly{
private:
int fa[maxn],ch[maxn][2],val[maxn],tot;
public:
inline void newnode(int &x,int father,int value){
x= ++tot; fa[x]=father; val[x]=value;
}
inline void Rotate(int x,int d){
int y=fa[x];
ch[y][!d]=ch[x][d];
fa[ch[x][d]]=y;
ch[x][d]=y;
if(fa[y]) ch[fa[y]][ch[fa[y]][1]==y]=x;
fa[x]=fa[y];
fa[y]=x;
}
void Splay(int x,int goal){
while(fa[x]!=goal){
int y=fa[x];
int d= (ch[y][0]==x);
if(fa[y]==goal) Rotate(x,d);
else{
d= (ch[fa[y]][0]==y);
if(ch[y][!d]==x){
Rotate(y,d);
Rotate(x,d);
} else{
Rotate(x,!d);
Rotate(x,d);
}
}
}
root=x;
}
inline int insert(int x){
int cur=root;
while(ch[cur][x>val[cur]]){
if(x==val[cur]) { Splay(cur,0);return 0; }
cur=ch[cur][x>val[cur]];
}
if(x==val[cur]) { Splay(cur,0);return 0; }
newnode(ch[cur][x>val[cur]],cur,x);
Splay(ch[cur][x>val[cur]],0);
return 1;
}
inline int Get_Pre(int x){
int cur=ch[x][0];
if(!cur) return INF*(-1);
while(ch[cur][1]) cur=ch[cur][1];
return val[cur];
}
inline int Get_Suf(int x){
int cur=ch[x][1];
if(!cur) return -INF;
while(ch[cur][0]) cur=ch[cur][0];
return val[cur];
}
}tre;
int main(){
int n,x;
scanf("%d",&n);
for(int i=1;i<=n;i++){
scanf("%d",&x);
if(i==1){
ans+=x;
tre.newnode(root,0,x);
}
else {
if(!tre.insert(x)) continue;
int a=tre.Get_Pre(root);
int b=tre.Get_Suf(root);
ans+=min(fabs(x-a),fabs(x-b));
}
}
printf("%d\n",ans);
return 0;
}
/*按照二叉排序树的定义 只有他的前驱或者后继肯能与他的
差的绝对值最小,所以ans加的时候,查一下前驱、后继
*/