前言
最近正值清明節放假,自己花時間刷了一些PAT,感覺很不錯。
問題描述
現有N個大理石,每個大理石上寫了一個非負整數、首先把各數從小到大排序;然後回答Q個問題。每個問題問是否有一個大理石寫着某個整數x,如果是,還要回答哪個大理石上寫着x。排序後的大理石從左到右編號爲1~N。
輸入大理石數量和需要回答問題數量,然後輸入大理石上的每個非負整數,接着輸入x
樣例輸入:
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
算法思路
這裏主要是排序函數(sort)和查找函數(lower_bound)的使用,沒有其他的算法實現。
代碼實現
#include<iostream>
#include<algorithm>
#include<string.h>
#define MAX 105
using namespace std;
int main() {
int m, n, k=0, x;
int a[MAX];
int b[MAX];
memset(a, 0, sizeof(a));
while(scanf("%d%d", &m,&n) == 2 && m) {
for(int i=0; i<m; i++) scanf("%d", &a[i]);
sort(a, a+m);
printf("CASE# %d:\n", ++k);
while(n--) {
scanf("%d", &x);
int pos = lower_bound(a, a+m, x) - a;
if(a[pos] == x) printf("%d found at %d\n", x, pos);
else printf("%d not found\n", x);
}
}
return 0;
}