10474 Where is the Marble?
題目原文
題目說明
第一行輸入兩個數字 N 和 Q,分別代表:有 N 個大理石和查找 Q 個數。
接下來的 N 行代表大理石所寫上的數,由小到大依序排列,最後求題目所問某數在哪個位置。
思路
利用 algorithm 裡的 sort 進行排序,再利用 lower_bound 查找出位置。
lower_bound :用來找出第一個大於或等於某數的位置。
題目說明
第一行輸入兩個數字 N 和 Q,分別代表:有 N 個大理石和查找 Q 個數。
接下來的 N 行代表大理石所寫上的數,由小到大依序排列,最後求題目所問某數在哪個位置。
思路
利用 algorithm 裡的 sort 進行排序,再利用 lower_bound 查找出位置。
lower_bound :用來找出第一個大於或等於某數的位置。
#include<cstdio>
#include<algorithm>
using namespace std;
const int maxn = 10000;
int main()
{
int n, q, arr[maxn], count = 0;
while(scanf("%d %d", &n, &q) == 2 && n)
{
printf("CASE# %d:\n", ++count);
for(int i = 0; i < n; i++)
scanf("%d", &arr[i]);
sort(arr, arr+n);
while(q--)
{
int num; // 要搜尋的數
scanf("%d", &num);
int pos = lower_bound(arr, arr+n, num) - arr; // 用 lower_bound 查找 num 的位置
if(arr[pos] == num)
printf("%d found at %d\n", num, pos+1);
else
printf("%d not found\n", num);
}
}
}
留言
張貼留言