1. 程式人生 > >bzoj1588:[HNOI2002]營業額統計

bzoj1588:[HNOI2002]營業額統計

情況 col -1 前驅後繼 sig 可能 問題 scanf oot

Description

營業額統計 Tiger最近被公司升任為營業部經理,他上任後接受公司交給的第一項任務便是統計並分析公司成立以來的營業情況。 Tiger拿出了公司的賬本,賬本上記錄了公司成立以來每天的營業額。分析營業情況是一項相當復雜的工作。由於節假日,大減價或者是其他情況的時候,營業額會出現一定的波動,當然一定的波動是能夠接受的,但是在某些時候營業額突變得很高或是很低,這就證明公司此時的經營狀況出現了問題。經濟管理學上定義了一種最小波動值來衡量這種情況: 該天的最小波動值 當最小波動值越大時,就說明營業情況越不穩定。 而分析整個公司的從成立到現在營業情況是否穩定,只需要把每一天的最小波動值加起來就可以了。你的任務就是編寫一個程序幫助Tiger來計算這一個值。 第一天的最小波動值為第一天的營業額。 ? 輸入輸出要求

Input

第一行為正整數 ,表示該公司從成立一直到現在的天數,接下來的n行每行有一個整數(有可能有負數) ,表示第i 天公司的營業額。 天數n<=32767, 每天的營業額ai <= 1,000,000。 最後結果T<=2^31

Output

輸出文件僅有一個正整數,即Sigma(每天最小的波動值) 。結果小於2^31 。

Sample Input

6
5
1
2
5
4
6

Sample Output

12

HINT

題解

先查前驅後繼,再插入。

  1 #include<cstdio>
  2
#include<algorithm> 3 #include<cstring> 4 #define inf 1<<29 5 #define maxn 50000 6 int cnt,flag,n,root,ret,ansx; 7 using namespace std; 8 struct treap{ 9 int lc,rc,key,pri,siz,val; 10 }a[maxn]; 11 void pushup(int o) 12 { 13 a[o].siz=a[a[o].lc].siz+a[a[o].rc].siz+a[o].val;
14 } 15 void lturn(int &o) 16 { 17 int t=a[o].rc; 18 a[o].rc=a[t].lc; 19 a[t].lc=o; 20 a[t].siz=a[o].siz; 21 pushup(o); 22 o=t; 23 return ; 24 } 25 void rturn(int &o) 26 { 27 int t=a[o].lc; 28 a[o].lc=a[t].rc; 29 a[t].rc=o; 30 a[t].siz=a[o].siz; 31 pushup(o); 32 o=t; 33 return ; 34 } 35 void insert(int &o,int x) 36 { 37 if(!o) 38 { 39 o=++cnt; 40 a[o]=(treap){0,0,x,rand(),1,1}; 41 return ; 42 } 43 a[o].siz++; 44 if(a[o].key==x)a[o].val++; 45 else if(a[o].key>x) 46 { 47 insert(a[o].lc,x); 48 if(a[a[o].lc].pri>a[o].pri)rturn(o); 49 } 50 else 51 { 52 insert(a[o].rc,x); 53 if(a[a[o].rc].pri>a[o].pri)lturn(o); 54 } 55 } 56 void que_pro(int o,int x) 57 { 58 if(!o)return ; 59 if(a[o].key==x) 60 { 61 ret=a[o].key; 62 return ; 63 } 64 if(a[o].key>x)que_pro(a[o].lc,x); 65 else 66 { 67 ret=a[o].key; 68 que_pro(a[o].rc,x); 69 } 70 return ; 71 } 72 void que_sub(int o,int x) 73 { 74 if(!o)return ; 75 if(a[o].key==x) 76 { 77 ret=a[o].key; 78 return ; 79 } 80 if(a[o].key<x)que_sub(a[o].rc,x); 81 else 82 { 83 ret=a[o].key; 84 que_sub(a[o].lc,x); 85 } 86 return ; 87 } 88 void work(int x) 89 { 90 int ans=inf; 91 ret=-inf; 92 que_pro(root,x); 93 ans=min(ans,abs(x-ret)); 94 ret=inf; 95 que_sub(root,x); 96 ans=min(ans,abs(x-ret)); 97 ansx+=ans; 98 return ; 99 } 100 int main() 101 { 102 int k; 103 scanf("%d",&n); 104 scanf("%d",&k); 105 srand(n); 106 ansx=k; 107 insert(root,k); 108 for(int i=1 ; i<n ; ++i) 109 { 110 scanf("%d",&k); 111 work(k);insert(root,k); 112 } 113 printf("%d",ansx); 114 return 0; 115 }

結果說明:5+|1-5|+|2-1|+|5-5|+|4-5|+|6-5|=5+4+1+0+1+1=12

bzoj1588:[HNOI2002]營業額統計