BZOJ 1588 营业额统计
题目描述 Description
Tiger最近被公司升任为营业部经理,他上任后接受公司交给的第一项任务便是统计并分析公司成立以来的营业情况。Tiger拿出了公司的账本,账本上记录了公司成立以来每天的营业额。分析营业情况是一项相当复杂的工作。由于节假日,大减价或者是其他情况的时候,营业额会出现一定的波动,当然一定的波动是能够接受的,但是在某些时候营业额突变得很高或是很低,这就证明公司此时的经营状况出现了问题。经济管理学上定义了一种最小波动值来衡量这种情况:该天的最小波动值 当最小波动值越大时,就说明营业情况越不稳定。而分析整个公司的从成立到现在营业情况是否稳定,只需要把每一天的最小波动值加起来就可以了。你的任务就是编写一个程序帮助Tiger来计算这一个值。第一天的最小波动值为第一天的营业额
输入描述 Input Description
第一行为正整数 ,表示该公司从成立一直到现在的天数,接下来的n行每行有一个整数(有可能有负数) ,表示第i天公司的营业额。
输出描述 Output Description
仅有一个正整数,即Sigma(每天最小的波动值)
样例输入 Sample Input
6
5
1
2
5
4
6
样例输出 Sample Output
12
数据范围及提示 Data Size & Hint
n<=32767,ai≤1000000
答案保证在INT32整形范围内
分析:
此题目的是找到和当前值差的绝对值最小的点,那么可以用Splay维护一个有序数列,然后插入查询前驱后继比较大小即可
实现:
查询前驱:该点左子树的最右侧节点
int pre() {
int now=ch[root][0];
while(ch[now][1]) now=ch[now][1];
return now;
}
查询后继:该点右子树的最左侧节点
int next() {
int now=ch[root][1];
while(ch[now][0]) now=ch[now][0];
return now;
}
insert按key值查找应该插入的位置即可
Code:
#include <bits/stdc++.h>
using namespace std;
#define inf 2100000000
#define maxn 1000000
int ch[maxn][2],key[maxn],f[maxn],cnt[maxn],size[maxn];
int root,sz,n;
int read() {
int ans=0,flag=1;
char ch=getchar();
while( (ch>'9' || ch<'0') && ch!='-' ) ch=getchar();
if(ch=='-') flag=-1,ch=getchar();
while(ch>='0' && ch<='9') ans=ans*10+ch-'0',ch=getchar();
return ans*flag;
}
bool get(int x) {return ch[f[x]][1]==x;}
void update(int x) {
size[x]=cnt[x]+size[ch[x][0]]+size[ch[x][1]];
return ;
}
void rotate(int x) {
int old=f[x],oldf=f[old],whichx=get(x);
ch[old][whichx]=ch[x][whichx^1];
f[ch[old][whichx]]=old;
ch[x][whichx^1]=old;
f[old]=x;
f[x]=oldf;
if(oldf)
ch[oldf][ch[oldf][1]==old]=x;
update(old);
update(x);
return ;
}
void splay(int x,int tar) {
for(int fa;(fa=f[x])!=tar;rotate(x))
if(f[fa]!=tar)
rotate(get(x)==get(fa)?fa:x);
if(!tar)
root=x;
return ;
}
int pre() {
int now=ch[root][0];
while(ch[now][1]) now=ch[now][1];
return now;
}
int next() {
int now=ch[root][1];
while(ch[now][0]) now=ch[now][0];
return now;
}
void insert(int x) {
if(root==0) {
sz++;
ch[sz][0]=ch[sz][1]=f[sz]=0;
root=sz;
cnt[sz]=size[sz]=1;
key[sz]=x;
return ;
}
int now=root,fa=0;
while(1) {
if(x==key[now]) {
cnt[now]++;
update(now);
update(fa);
splay(now,0);
break;
}
fa=now;
now=ch[now][key[now]<x];
if(now==0) {
sz++;
ch[sz][0]=ch[sz][1]=0;
f[sz]=fa;
cnt[sz]=size[sz]=1;
ch[fa][key[fa]<x]=sz;
key[sz]=x;
update(fa);
splay(sz,0);
break;
}
}
return ;
}
int main() {
n=read();
int ans=0;
for(int i=1;i<=n;i++) {
int x=read();
insert(x);
if(i==1) {
ans+=x;
continue;
}
if(cnt[root]==1) {
int l,r;
if(pre()==0) l=inf;
else l=key[pre()];
if(next()==0) r=inf;
else r=key[next()];
ans+=min(abs(x-l),abs(x-r));
}
}
printf("%d",ans);
return 0;
}