1588: [HNOI2002]营业额统计
Time Limit: 5 Sec Memory Limit: 162 MBSubmit: 12474 Solved: 4503
[ Submit][ Status][ Discuss]
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
此题数据有问题,详见讨论版http://www.lydsy.com/JudgeOnline/wttl/wttl.php?pid=1588
题解:splay裸题,以权值为关键字建树。
(貌似bzoj 上数据有问题,可以从code vs 上提交)
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#define N 50000
using namespace std;
int n,m,sum,root,sz;
int key[N],size[N],cnt[N],ch[N][3],fa[N];
const int inf=1e9;
void clear(int x)
{
fa[x]=key[x]=size[x]=cnt[x]=ch[x][1]=ch[x][0]=0;
}
void update(int x)
{
size[x]=size[ch[x][0]]+size[ch[x][1]]+cnt[x];
}
int get(int x)
{
return ch[fa[x]][1]==x;
}
void rotate(int x)
{
int y=fa[x]; int z=fa[y]; int which=get(x);
if (z) ch[z][ch[z][1]==y]=x;
ch[y][which]=ch[x][which^1]; fa[ch[x][which^1]]=y;
ch[x][which^1]=y; fa[y]=x; fa[x]=z;
update(y); update(x);
}
void splay(int x)
{
for (int f;(f=fa[x]);rotate(x))
if (fa[f]) rotate(get(x)==get(f)?f:x);
root=x;
}
void insert(int x)
{
if (!root)
{
sz++; root=sz; clear(sz); size[sz]=cnt[sz]=1; key[sz]=x; return;
}
int now=root;
while(true)
{
if (x==key[now])
{
cnt[now]++; update(now); splay(now); return;
}
int f=now;
now=ch[now][x>key[now]];
if (!now)
{
sz++; ch[f][x>key[f]]=sz; clear(sz); size[sz]=cnt[sz]=1;
key[sz]=x; fa[sz]=f; update(f); splay(sz); 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;
}
int main()
{
scanf("%d",&n);
for (int i=1;i<=n;i++)
{
int x; scanf("%d",&x);
insert(x);
if(i!=1)
{
if (cnt[root]>1) continue;
if (pre()&&next())
sum+=min(abs(key[pre()]-x),abs(key[next()]-x));
else
if (pre()) sum+=abs(key[pre()]-x);
else
if (next()) sum+=abs(key[next()]-x);
}
else
sum=x;
}
printf("%d\n",sum);
}