【题目】
题目描述:
Tiger 最近被公司升任为营业部经理,他上任后接受公司交给的第一项任务便是统计并分析公司成立以来的营业情况。
Tiger 拿出了公司的账本,账本上记录了公司成立以来每天的营业额。分析营业情况是一项相当复杂的工作。由于节假日,大减价或者是其他情况的时候,营业额会出现一定的波动,当然一定的波动是能够接受的,但是在某些时候营业额突变得很高或是很低,这就证明公司此时的经营状况出现了问题。经济管理学上定义了一种最小波动值来衡量这种情况:
该天的最小波动值= { | 该天以前某一天的营业额-该天营业额 | }
当最小波动值越大时,就说明营业情况越不稳定。
而分析整个公司的从成立到现在营业情况是否稳定,只需要把每一天的最小波动值加起来就可以了。你的任务就是编写一个程序帮助 Tiger 来计算这一个值(规定:第一天的最小波动值为第一天的营业额)。
输入格式:
第一行为正整数 ( ≤ 32767) ,表示该公司从成立一直到现在的天数。
接下来的 行每行有一个正整数 ( ≤ 1000000),表示第 天公司的营业额。
输出格式:
输出一个正整数,即:∑每一天的最小波动值 。结果小于 。
样例数据:
输入
6 5 1 2 5 4 6
输出
12
备注:
【样例说明】
【分析】
平衡树模板题。。。
有一些小小的细节,就是每一个数 应查询后再插入,不然的话会一直是 0
【代码】
#include<ctime>
#include<cstdio>
#include<cstring>
#include<algorithm>
#define N 40000
#define lc(x) son[x][0]
#define rc(x) son[x][1]
#define inf (1ll<<30ll)
using namespace std;
int tot,num[N],val[N],size[N],weight[N],son[N][2];
void pushup(int x)
{
size[x]=size[lc(x)]+size[rc(x)]+num[x];
}
void rotate(int &root,int t)
{
int x=son[root][t];
son[root][t]=son[x][t^1];
son[x][t^1]=root;
pushup(root),pushup(x);
root=x;
}
void insert(int &root,int x)
{
if(root)
{
if(val[root]==x)
num[root]++;
else
{
int t=val[root]<x;
insert(son[root][t],x);
if(weight[son[root][t]]<weight[root])
rotate(root,t);
}
}
else
{
root=++tot;
val[root]=x;
num[root]=1;
weight[root]=rand();
}
pushup(root);
}
int findpre(int root,int x)
{
if(!root) return -inf;
if(val[root]<=x) return max(val[root],findpre(rc(root),x));
return findpre(lc(root),x);
}
int findsuf(int root,int x)
{
if(!root) return inf;
if(val[root]>=x) return min(val[root],findsuf(lc(root),x));
return findsuf(rc(root),x);
}
int main()
{
int n,i,x,l,r;
int ans,root=0;
srand(time(0));
scanf("%d%d",&n,&x);
insert(root,x),ans=x;
for(i=2;i<=n;++i)
{
scanf("%d",&x);
l=findpre(root,x);
r=findsuf(root,x);
ans+=min(x-l,r-x);
insert(root,x);
}
printf("%d",ans);
return 0;
}