UVA - 10474 Where is the Marble?

来源:互联网 发布:ubuntu中文语言包 apt 编辑:程序博客网 时间:2024/04/30 06:22

主要就是熟悉一下lower_bound;


#include <iostream>
#include <algorithm>
using namespace std;
const int maxn=10011;
int a[maxn];

int main()
{
    int n, q, ncase=0;
    while(cin>>n>>q,q!=0&&n!=0)
    {
        cout<<"CASE# "<<++ncase<<":"<<endl;
        for(int i=0;i<n;i++)
        {
            cin>>a[i];
        }
        sort(a,a+n);
        for(int i=0;i<q;i++)
        {
            int x;
            cin>>x;
            int p=lower_bound(a,a+n,x)-a;
            if(a[p]==x)
            {
                cout<<x<<" found at "<<p+1<<endl;
            }
            else
            {
                cout<<x<<" not found"<<endl;
            }
        }
    }
    return 0;
}



函数作用

编辑
升序排列的容器:
iteratorlower_bound( const key_type &key ): 返回一个迭代器,指向键值>= key的第一个元素。
iterator upper_bound( const key_type &key ):返回一个迭代器,指向键值>key的第一个元素。
★降序排列的容器:
iteratorlower_bound( const key_type &key ): 返回一个迭代器,指向键值<= key的第一个元素。
iterator upper_bound( const key_type &key ):返回一个迭代器,指向键值<key的第一个元素。

举例

编辑
例如:map中已经插入了1,2,3,4的话,如果lower_bound(2)的话,返回的2,而upper_bound(2)的话,返回的就是3
equal_range函数返回一个pair,pair里面第一个变量是lower_bound返回的迭代器,pair里面第二个迭代器是upper_bound返回的迭代器,如果这两个迭代器相等的话,则说明map中不出现这个关键字,程序说明
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include<map>
#include<string>
#include<iostream>
usingnamespacestd;
intmain()
{
map<int,string>mapStudent;
mapStudent[1]="student_one";
mapStudent[3]="student_three";
mapStudent[5]="student_five";
map<int,string>::iterator iter;
iter=mapStudent.lower_bound(2);
{
//返回的是下界3的
迭代器
cout<<iter->second<<
endl;
}
iter=mapStudent.lower_bound(3);
{
//返回的是下界5的迭代器
cout<<iter->second<<endl;
}
iter=mapStudent.upper_bound(2);
{
//返回的是上界3的迭代器
cout<<iter->second<<
endl;
}
iter=mapStudent.upper_bound(3);
{
//返回的是上界5的
迭代器
cout<<iter->second<<endl;
}
return0;
}






0 0
原创粉丝点击