P2234 [HNOI2002]营业额统计

s.lower_bound(x):二分出序列中最小的>=x的迭代器
s.upper_bound(x):二分出序列中最小的>x的迭代器

#include<iostream>
#include<set>
#include<cmath>

using namespace std;

const int N = 40010;

set<int> s;
int n;

int main(){
    cin >> n;
    
    int res = 0;
    
    while(n --){
        int x;
        
        cin >> x;
        
        int ans = x;
        
        if(s.size()){
            set<int> :: iterator it = s.lower_bound(x);
            ans = abs(*it - x);
            if(it != s.begin()) -- it;
            ans = min(abs(*it - x), ans);
        }
        
        s.insert(x);
        
        res += ans;
    }
    
    cout << res;
    
    return 0;
}
posted @ 2020-10-21 10:20  yys_c  阅读(88)  评论(0编辑  收藏  举报