bzoj - 1588 營業額統計 (Splay裸題)

1588: [HNOI2002]營業額統計

Time Limit: 5 Sec  Memory Limit: 162 MB
Submit: 16991  Solved: 6843
[Submit][Status][Discuss]

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

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


該題數據bug已修復.----2016.5.15

Source


#include <bits/stdc++.h>
using namespace std;

const int N = 1e5 + 10;
int n;
int root, tot;
int v[N], ch[N][2], fa[N];

void Init(){
    root = tot = 0;
    v[0] = ch[0][0] = ch[0][1] = fa[0] = 0;
}

void Newnode(int &k, int f, int V){
    k = ++tot;
    fa[k] = f;
    ch[k][0] = ch[k][1] = 0;
    v[k] = V;
}

void Rotate(int x, int kind){
    int y = fa[x];
    int z = fa[y];
    ch[y][!kind] = ch[x][kind];
    fa[ch[x][kind]] = y;
    if(z) ch[z][ch[z][1] == y] = x;
    fa[x] = z;
    fa[y] = x;
    ch[x][kind] = y;
}

void Splay(int x, int goal){
    while(fa[x] != goal){
        if(fa[fa[x]] == goal) Rotate(x, ch[fa[x]][0] == x);
        else{
            int y = fa[x];
            int z = fa[y];
            int kind = ch[z][0] == y;
            if(ch[y][kind] == x){
                Rotate(x, !kind);
                Rotate(x, kind);
            }
            else{
                Rotate(y, kind);
                Rotate(x, kind);
            }
        }
        if(!goal) root = x;
    }
}

void Insert(int V){
    int k = root;
    while(ch[k][v[k] < V]){
        k = ch[k][v[k] < V];
    }
    Newnode(ch[k][v[k] < V], k, V);
    Splay(ch[k][v[k] < V], 0);
}

int Get_min(int k){
    while(ch[k][0]) k = ch[k][0];
    return k;
}

int Get_max(int k){
    while(ch[k][1]) k = ch[k][1];
    return k;
}

int main(){
    while(scanf("%d", &n) == 1){
        Init();
        int ans = 0;
        for(int i = 0; i < n; i++){
            int x;
            scanf("%d", &x);
            Insert(x);
            if(!i) ans += x;
            else{
                int tmp = 0x3f3f3f3f;
                if(ch[root][0]) tmp = min(tmp, v[root] - v[Get_max(ch[root][0])]);
                if(ch[root][1]) tmp = min(tmp, v[Get_min(ch[root][1])] - v[root]);
                ans += tmp;
            }
        }
        printf("%d\n", ans);
    }
}


發佈了133 篇原創文章 · 獲贊 5 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章