UVa - 10474 Where is the Marble?(STL)

题目链接:http://acm.hust.edu.cn/vjudge/problem/viewProblem.action?id=19833

#include <iostream>
#include <algorithm>
#define MAX 10005
using namespace std;
/**************************************************************************************************************
       1, 函数lower_bound()在first和last中的前闭后开区间进行二分查找,返回大于或等于val的第一个元素位置。
        如果所有元素都小于val,则返回last的位置
       2, 举例如下:
            一个数组number序列为:4,10,11,30,69,70,96,100.设要插入数字3,9,111.pos为要插入的位置的下标
        则
            a:pos = lower_bound( number, number + 8, 3) - number,pos = 0.
              即number数组的下标为0的位置。
            b:pos = lower_bound( number, number + 8, 9) - number, pos = 1,
              即number数组的下标为1的位置(即10所在的位置)。
            c:pos = lower_bound( number, number + 8, 111) - number, pos = 8,
              即number数组的下标为8的位置(但下标上限为7,所以返回最后一个元素的下一个元素)。
        3,所以,要记住:函数lower_bound()在first和last中的前闭后开区间进行二分查找,返回大于或等于val的第一个
        元素位置。如果所有元素都小于val,则返回last的位置,且last的位置是越界的!!~

        4,返回查找元素的第一个可安插位置,也就是“元素值>=查找值”的第一个元素的位置
**************************************************************************************************************/
int a[MAX];
int main()
{
    int n,t,kase=0;
    while(cin>>n>>t)
    {
        cout<<"CASE# "<<++kase<<":"<<endl;
        for(int i = 1;i <= n;i ++)  cin>>a[i];
        sort(a+1,a+n+1);
        while(t--)
        {
            int ans;
            cin>>ans;
            int id=lower_bound(a+1,a+n+1,ans)-a;
            if(a[id] == ans)
                cout<<ans<<" found at "<<id<<endl;
            else
                cout<<ans<<" not found"<<endl;
        }
    }
    return 0;
}


posted on 2016-05-10 00:12  Jstyle  阅读(109)  评论(0编辑  收藏  举报

导航