[BZOJ] 1588 [HNOI2002]营业额统计

Time Limit: 5 Sec  Memory Limit: 162 MB
Submit: 18888  Solved: 7955
[Submit][Status][Discuss]
Description
营业额统计 Tiger最近被公司升任为营业部经理,他上任后接受公司交给的第一项任务便是统计并分析公司成立以来的营业情况。 Tiger拿出了公司的账本,账本上记录了公司成立以来每天的营业额。分析营业情况是一项相当复杂的工作。由于节假日,大减价或者是其他情况的时候,营业额会出现一定的波动,当然一定的波动是能够接受的,但是在某些时候营业额突变得很高或是很低,这就证明公司此时的经营状况出现了问题。经济管理学上定义了一种最小波动值来衡量这种情况: 该天的最小波动值 当最小波动值越大时,就说明营业情况越不稳定。 而分析整个公司的从成立到现在营业情况是否稳定,只需要把每一天的最小波动值加起来就可以了。你的任务就是编写一个程序帮助Tiger来计算这一个值。 第一天的最小波动值为第一天的营业额。    输入输出要求

Input
第一行为正整数 ,表示该公司从成立一直到现在的天数,接下来的n行每行有一个整数(有可能有负数) ,表示第i
天公司的营业额。
天数n<=32767,
每天的营业额ai <= 1,000,000。
最后结果T<=2^31
Output
输出文件仅有一个正整数,即Sigma(每天最小的波动值) 。结果小于2^31Sample Input
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


该题数据bug已修复.----2016.5.15

单点插入,求前驱后继,splay最擅长了,嗯。
set也行,听说排序都行..

#include<iostream>
#include<cstdio>

using namespace std;

inline int rd(){
  int ret=0,f=1;char c;
  while(c=getchar(),!isdigit(c))f=c=='-'?-1:1;
  while(isdigit(c))ret=ret*10+c-'0',c=getchar();
  return ret*f;
}

const int MAXN=1048576;
const int INF=1<<29;

int val[MAXN],ch[MAXN][2],fa[MAXN];
int root,tot;
inline bool check(int x){return x==ch[fa[x]][1];}
inline int newnode(int x){val[++tot]=x;return tot;}
void rotate(int x){
  int y=fa[x],z=fa[fa[x]];
  bool ck=check(x);
  fa[ch[x][ck^1]]=y;ch[y][ck]=ch[x][ck^1];
  ch[x][ck^1]=y;fa[y]=x;fa[x]=z;
  if(z) ch[z][ch[z][1]==y]=x;
}
void splay(int x){
  for(int f=fa[x];f;rotate(x),f=fa[x])
    if(fa[f]) rotate(check(x)==check(f)?f:x);
  root=x;
}
bool insert(int x){
  if(!root){root=newnode(x);return 1;}
  int cur=root,f=0;
  while(1){
    if(val[cur]==x)return splay(cur),0;
    f=cur;cur=ch[cur][x>val[cur]];
    if(!cur){cur=newnode(x);fa[cur]=f;ch[f][x>val[f]]=cur;splay(cur);return 1;}
  }
}
int pre(){
  int cur=ch[root][0];
  while(ch[cur][1]) cur=ch[cur][1];
  return val[cur];
}
int nxt(){
  int cur=ch[root][1];
  while(ch[cur][0]) cur=ch[cur][0];
  return val[cur];
}

int n;

int main(){
  int ans=0,x;
  n=rd();insert(-INF);insert(INF);
  int v1=rd();insert(v1);
  for(int i=2;i<=n;i++){
    x=rd();
    if(!insert(x)) continue;
    ans+=min(x-pre(),nxt()-x);
  }
  printf("%d",ans+v1);
  return 0;
}

猜你喜欢

转载自blog.csdn.net/gh0stcai/article/details/80685669