【Treap】bzoj1588-HNOI2002營業額統計

1、題目

Description

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

Input

第一行爲正整數 ,表示該公司從成立一直到如今的天數,接下來的n行每行有一個整數(有可能有負數) ,表示第i天公司的營業額。html

Output

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

Sample Input

6
5
1
2
5
4
6ide

Sample Output

12spa

HINT

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

順便附上原題連接→_→Problem1588. -- [HNOI2002]營業額統計htm

2、代碼實現

裸treap,沒什麼好說的┑( ̄Д  ̄)┍blog

 1 #include<cstdio>
 2 #include<cstdlib>
 3 #include<algorithm>
 4 using namespace std;
 5 const int MAXN=5e4+10;
 6 const int INF=1e9+1e8;
 7 int n;
 8 struct node
 9 {
10     int key,pri,l,r;//關鍵字、優先級、左兒子編號、右兒子編號
11 }tr[MAXN];
12 int root,p,s,ptot;
13 void query_pre(int k,int x)
14 {
15     if(!k)return;
16     if(x<tr[k].key)query_pre(tr[k].l,x);
17     else
18     {
19         p=tr[k].key;
20         query_pre(tr[k].r,x);
21     }
22     return;
23 }
24 void query_sub(int k,int x)
25 {
26     if(!k)return;
27     if(x>tr[k].key)query_sub(tr[k].r,x);
28     else
29     {
30         s=tr[k].key;
31         query_sub(tr[k].l,x);
32     }
33     return;
34 }
35 void turn_left(int &k)
36 {
37     int temp=tr[k].r;
38     tr[k].r=tr[temp].l;
39     tr[temp].l=k;
40     k=temp;
41     return;
42 }
43 void turn_right(int &k)
44 {
45     int temp=tr[k].l;
46     tr[k].l=tr[temp].r;
47     tr[temp].r=k;
48     k=temp;
49     return;
50 }
51 void insert(int &k,int x)
52 {
53     if(!k)
54     {
55         k=++ptot;
56         tr[k].key=x;
57         tr[k].pri=rand();
58         return;
59     }
60     if(tr[k].key==x)return;
61     else if(x<tr[k].key)
62     {
63         insert(tr[k].l,x);
64         if(tr[k].pri<tr[tr[k].l].pri)turn_right(k);
65     }
66     else 
67     {
68         insert(tr[k].r,x);
69         if(tr[k].pri<tr[tr[k].r].pri)turn_left(k);
70     }
71     return;
72 }
73 int main()
74 {
75     scanf("%d",&n);
76     srand(n);
77     int ans=0;
78     for(int i=1;i<=n;++i)
79     {
80         int x;
81         scanf("%d",&x);
82         if(i==1)ans=x;
83         else
84         {
85             p=-INF,s=INF;
86             query_pre(root,x);
87             query_sub(root,x);
88             ans+=min(x-p,s-x);
89         }
90         insert(root,x);
91     }
92     printf("%d\n",ans);
93     return 0;
94 }
Problem1588. -- [HNOI2002]營業額統計

弱弱地說一句,本蒟蒻碼字也不容易,轉載請註明出處http://www.cnblogs.com/Maki-Nishikino/p/6236211.htmlip

相關文章
相關標籤/搜索