Set 技巧之一

     我们知道set中 用set<int,int>S;

                               S.lower_bound(x): 查找Set中 第一个>=x的数,返回结果是指针。

                               S.upper_bound(x):查找Set中 第一个大于x的数,返回结果是指针。

如果想要找到set中小于等于(x)的数,我们可以这样做:

                               set<int>::iterator it

                               it=--S.upper_bound(x);

                               第一个大于x的前一个一定小于等于x

                              如果是找set中小于x的数,我们可以

                              it=--S.lower_bound(x);

                              第一个大于等于x的前一个 一定小于x;

所以BZOJ  1588: [HNOI2002]营业额统计 可以只用set 写出来

#include<stdio.h>
#include<algorithm>
#include<math.h>
#include<vector>
#include<string.h>
#include<string>
#include<set>
#include<map>
#include<iostream>
#include<set>
using namespace std;
typedef long long ll;
#define N 33333
set<int>S;
set<int>::iterator it,itt;

int main()
{
    int n;
    while (scanf("%d",&n)!=EOF)
    {
        S.clear();
        int ans=0;
        int x;

        S.insert(-999999999);
        S.insert(999999999);

        for (int i=1;i<=n;i++)
        {
            if (scanf("%d",&x)==EOF) x=0;
            if (i==1)
            {
              ans+=x;
              S.insert(x);
              continue;
            }
            it=S.lower_bound(x);
            itt=S.upper_bound(x);
            int tmp=abs(x-(*it));
            int tmpp=abs(x-(*(--it)));
            ans+=min(tmp,tmpp);
            S.insert(x);
        }
        printf("%d\n",ans);
    }
    return 0;
}

一定得先insert 一个最大最小。

 

posted on 2015-07-05 18:46  forgot93  阅读(1064)  评论(0编辑  收藏  举报

导航