STL-set-详解-uva10474

大理石在哪儿
现有N个大理石,每个大理石上写了一个非负整数、首先把各数从小到大排序
然后回答Q个问题。每个问题问是否有一个大理石写着某个整数x,如果是,还要
回答哪个大理石上写着x。排序后的大理石从左到右编号为1~N。(在样例中,为了
节约篇幅,所有大理石的数合并到一行,所有问题也合并到一行。)
样例输入:
4 1
2 3 5 1
5
5 2
1 3 3 3 1
2 3
样例输出:
CASE# 1:
5 found at 4
CASE# 2:
2 not found

3 found at 3 

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<math.h>
#include<set>
#define PI 3.1415926535897932384626
const int maxn=10000;
using namespace std;
/*set(排序,元素不重复) 使用方法
int main()
{
    set<int> s;
    s.insert(1);
    s.insert(2);
    s.insert(3);
    s.insert(1);
    cout<<"set 的 size 值为 :"<<s.size()<<endl;//3
    cout<<"set 的 maxsize的值为 :"<<s.max_size()<<endl;//1073741823
    cout<<"set 中的第一个元素是 :"<<*s.begin()<<endl;//1
    cout<<"set 中的最后一个元素是:"<<*s.end()<<endl;//-842150451
    s.clear();
    if(s.empty())
    {
        cout<<"set 为空 !!!"<<endl;//
    }
    cout<<"set 的 size 值为 :"<<s.size()<<endl;//0
    cout<<"set 的 maxsize的值为 :"<<s.max_size()<<endl;//1073741823
    cout<<"set 中 1 出现的次数是 :"<<s.count(1)<<endl;//1
    cout<<"set 中 4 出现的次数是 :"<<s.count(4)<<endl;//0
    cout<<*s.lower_bound(2)<<endl;//2
    return 0;
}
 */
 /*
set<int>::iterator it;
it=s.find(5);    //查找键值为5的元素
if(it!=s.end())    //找到
    cout<<*it<<endl;
else            //未找到
    cout<<"未找到";
*/
int main()
{
    set<int> st;//
    int n,q;
    int a[maxn];
    int k=1;
    while(scanf("%d%d",&n,&q)!=EOF)
    {
        if(n==0)break;
        st.clear(); //清空
        for(int i=0;i<n;i++)
        {
            scanf("%d",&a[i]);
        }
        sort(a,a+n);
        for(int i=0;i<n;i++)
        {
            st.insert(a[i]);//插入
        }
        printf("CASE# %d:\n",k++);
        while(q--)
        {
            int x;
            scanf("%d",&x);
            int p=lower_bound(a,a+n,x)-a;//返回数组a中x的位置
            if(a[p]==x)printf("%d found at %d\n",x,p+1);
            else printf("%d not found\n",x);

        }
    }
    return 0;
}








猜你喜欢

转载自blog.csdn.net/qq_41568836/article/details/81625378
今日推荐