HNOI 2002 营业额统计 Splay解法
地址:https://www.lydsy.com/JudgeOnline/problem.php?id=1588
题意:Tiger 最近被公司升任为营业部经理,他上任后接受公司交给的第一项任务便是统计并分析公司成立以来的营业情况。Tiger 拿出了公司的账本,账本上记录了公司成立以来每天的营业额。分析营业情况是一项相当复杂的工作。由于节假日,大减价或者是其他情况的时候,营业额会出现一定的波动,当然一定的波动是能够接受的,但是在某些时候营业额突变得很高或是很低,这就证明公司此时的经营状况出现了问题。经济管理学上定义了一种最小波动值来衡量这种情况,最小波动值= min { | 该天以前某一天的营业额-该天的营业额| },求最小波动值的和。注:第一天的最小波动值为第一天的营业额。
数据范围:天数n≤32767,每天的营业额ai≤1,000,000。最后结果T≤2^31。
进一步分析本题,解题中,涉及到对于有序集的三种操作:插入、求前趋、求后继。而对于这三种操作,伸展树的时间复杂度都非常优秀,于是我们设计了如下算法:开始时,树S 为空,总和T 为零。每次读入一个数p,执行Insert(p,S),将p插入伸展树S。这时,p 也被调整到伸展树的根节点。这时,求出p 点左子树中的最右点和右子树中的最左点,这两个点分别是有序集中p的前趋和后继。然后求得最小差值,加入最后结果T。
/************************************************************** Problem: 1588 User: h6363817 Language: C++ Result: Accepted Time:168 ms Memory:16896 kb ****************************************************************/ #include <iostream> #include<cstdio> #include<cstring> #include<algorithm> using namespace std; const int mm=1000005; const int oo=1e9; struct SplayTree { int son[mm][2],far[mm],val[mm]; int rt,size; void Link(int x,int y,int c) { //将x作为y的c儿子连接上 far[x]=y,son[y][c]=x; } void Rotate(int x,int c) { //c=0则x是y的左儿子 int y=far[x]; Link(x,far[y],son[far[y]][1]==y); Link(son[x][!c],y,c); Link(y,x,!c); } void Splay(int x,int g) { for(; far[x]!=g;) { int y=far[x],cy=(son[far[y]][1]==y),cx=(son[y][1]==x); if(far[y]==g)Rotate(x,cx); else { if(cx==cy)Rotate(y,cy); else Rotate(x,cx); Rotate(x,cy); } } if(!g)rt=x; } void NewNode(int y,int &x,int a) { x=++size; far[x]=y,val[x]=a; son[x][0]=son[x][1]=0; } void Prepare() { NewNode(size=0,rt,-oo); NewNode(rt,son[rt][1],oo); } void Insert(int a) { int x=rt; while(son[x][val[x]<a])x=son[x][val[x]<a]; NewNode(x,son[x][val[x]<a],a); Splay(size,0); } int Pre(int a) { int x=rt,ret=-oo; while(x) { if(val[x]==a)return a; if(val[x]<a)ret=max(ret,val[x]); x=son[x][val[x]<a]; } return ret; } int Suc(int a) { int x=rt,ret=oo; while(x) { if(val[x]==a)return a; if(val[x]>a)ret=min(ret,val[x]); x=son[x][val[x]<a]; } return ret; } } spt; int main() { int n,a,t; scanf("%d%d",&n,&a); t=a; spt.Prepare(); spt.Insert(a); while(--n) { if(scanf("%d",&a)==-1) a=0; t+=min(a-spt.Pre(a),spt.Suc(a)-a); spt.Insert(a); } printf("%d\n",t); return 0; }
最后更新:2017-04-03 16:48:56