大理石在哪~c++

大理石在哪儿
现有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 

本题主要运用了c++的STL(标准模板库)里的排序检索函数,这样做题会省很多时间。

#include<cstdio>
#include<algorithm>

using namespace std;

int main()
{
    int n,m,kace=0;
    while(scanf("%d%d",&n,&m)==2&&n)
    {
        int a[100];
        for(int i=0; i<n; i++)
        {
            scanf("%d",&a[i]);
        }
        sort(a,a+n);                  //排序函数
        printf("case %d:\n",++kase);
        while(m--)
        {
            int key;
            scanf("%d",&key);
            int i=lower_bound(a,a+n,key)-a;   //返回第一个不小于key的位置
            if(a[i]==key)                     
            {
                printf("%d found at %d\n",key,i+1);
            }
            else
            {
                printf("%d not found\n",key);
            }
        }
    }
    return 0;
}
 

猜你喜欢

转载自blog.csdn.net/myCsdn_Xm/article/details/81252030
今日推荐