[CODEVS 1285] 宠物收养所

http://codevs.cn/problem/1285/

题解

运用STL的set,和算法库(Algorithm)的upper_bound()与lower_bound(),实现log(n)的查找。要注意的是set类的upper_bound(x) 返回在集合中第一个大于x的元素,而lower_bound()返回在集合中第一个大于或等于x的元素,与它们在数组中的作用不太一样。

代码

总时间耗费: 657ms
总内存耗费: 748B

#include<cstdio>
#include<iostream>
#include<cstring>
#include<string>
#include<set>
#include<cmath>
#include<algorithm>
using namespace std;

set<int> S;
int main() {
    int n;
    bool flag;
    cin >> n;
    int ans = 0;
    for(int i = 1; i <= n; i++) {
        int a, b;
        cin >> a >> b;
        if(S.empty() || flag == a) {
            S.insert(b);
            flag = a;
        } else {
            set<int>::iterator it = S.lower_bound(b);
            int x = *it, y = (it == S.begin())? (*it) : *(--it);
            if(abs(b-x) <= abs(b-y)) S.erase(x); else S.erase(y);
            ans = (ans + min(abs(b-x), abs(b-y))) % 1000000;
        }
    }
    cout << ans << endl;
    return 0;
}

posted @ 2015-02-06 12:42  wfwbz  阅读(110)  评论(0编辑  收藏  举报