1588: [HNOI2002]营业额统计
Time Limit: 5 Sec Memory Limit: 162 MBSubmit: 8084 Solved: 2673
[ Submit][ Status]
Description
营业额统计 Tiger最近被公司升任为营业部经理,他上任后接受公司交给的第一项任务便是统计并分析公司成立以来的营业情况。 Tiger拿出了公司的账本,账本上记录了公司成立以来每天的营业额。分析营业情况是一项相当复杂的工作。由于节假日,大减价或者是其他情况的时候,营业额会出现一定的波动,当然一定的波动是能够接受的,但是在某些时候营业额突变得很高或是很低,这就证明公司此时的经营状况出现了问题。经济管理学上定义了一种最小波动值来衡量这种情况: 该天的最小波动值 当最小波动值越大时,就说明营业情况越不稳定。 而分析整个公司的从成立到现在营业情况是否稳定,只需要把每一天的最小波动值加起来就可以了。你的任务就是编写一个程序帮助Tiger来计算这一个值。 第一天的最小波动值为第一天的营业额。 输入输出要求
Input
第一行为正整数 ,表示该公司从成立一直到现在的天数,接下来的n行每行有一个正整数 ,表示第i天公司的营业额。
Output
输出文件仅有一个正整数,即Sigma(每天最小的波动值) 。结果小于2^31 。
Sample Input
6
5
1
2
5
4
6
5
1
2
5
4
6
Sample Output
12
HINT
结果说明:5+|1-5|+|2-1|+|5-5|+|4-5|+|6-5|=5+4+1+0+1+1=12
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int MAXN=100000+100;
const int inf=0x3fffffff;
int n,tot;
struct node
{
int v,s;
node *fa,*next[2];
}*root,*null;
node nod[MAXN];
node *ind[MAXN];
struct Splay
{
void init()
{
null=&nod[0]; tot=1;
null->v=-inf;
for(int i=0;i<MAXN;i++){
ind[i]=&nod[i];
nod[i].next[0]=nod[i].next[1]=null;
}
}
node *newnode(int v,node *f)
{
node *x=ind[tot++]; x->v=v; x->fa=f;
if(x->next[0]!=null) ind[--tot]=x->next[0];
if(x->next[1]!=null) ind[--tot]=x->next[1];
x->next[0]=x->next[1]=null;
int d= v<f->v ? 0 : 1;
f->next[d]=x;
return x;
}
void rotate(node *x,int d)
{
node *y=x->fa;
y->next[d^1]=x->next[d];
if(x->next[d]!=null) x->next[d]->fa=y;
x->fa=y->fa;
if(y->fa!=null){
int d1=y->fa->next[1] == y ? 1 : 0;
y->fa->next[d1]=x;
}
x->next[d]=y; y->fa=x;
if(y==root) root=x;
}
void splay(node *x,node *f)
{
while(x->fa!=f){
node *y=x->fa;
if(y->fa == f){
int d=y->next[0] == x ? 1 : 0;
rotate(x,d);
}
else {
int d=y->fa->next[0] == y ? 1 : 0;
if( y->next[d] == x){
rotate(x,d^1); rotate(x,d);
}
else {
rotate(y,d);rotate(x,d);
}
}
}
}
int insert(int v)
{
node *x=root;
int k=x->v;
if(k == v){
return 0;
}
while(x->next[k<v]!=null){
x=x->next[k<v];
if(x->v == v){
splay(x,null);
return 0;
}
k=x->v;
}
node *temp=newnode(v,x);
splay(temp,null);
return 1;
}
int get_pre(node *x)
{
node *tmp=x->next[0];
if(tmp == null)
return inf;
while(tmp->next[1]!=null)
tmp=tmp->next[1];
return x->v-tmp->v;
}
int get_next(node *x)
{
node *tmp=x->next[1];
if(tmp == null)
return inf;
while(tmp->next[0]!=null)
tmp=tmp->next[0];
return tmp->v-x->v;
}
}spt;
int main()
{
//freopen("text.txt","r",stdin);
while(~scanf("%d",&n)){
int ans=0; spt.init();
for(int i=1;i<=n;i++){
int num;
if(scanf("%d",&num)==EOF) num=0;
if(i == 1){
ans+=num;
root=spt.newnode(num,null);
continue;
}
if(spt.insert(num) == 0)
continue;
int a=spt.get_pre(root);
int b=spt.get_next(root);
ans+=min(a,b);
//printf("%d %d %d\n",num,a,b);
}
printf("%d\n",ans);
}
return 0;
}