10474 Where is the Marble?

題目原文

題目說明
第一行輸入兩個數字 N 和 Q,分別代表:有 N 個大理石和查找 Q 個數。
接下來的 N 行代表大理石所寫上的數,由小到大依序排列,最後求題目所問某數在哪個位置。

思路
利用 algorithm 裡的 sort 進行排序,再利用 lower_bound 查找出位置。
lower_bound :用來找出第一個大於或等於某數的位置。

  1. #include<cstdio>
  2. #include<algorithm>
  3. using namespace std;
  4.  
  5. const int maxn = 10000;
  6.  
  7. int main()
  8. {
  9. int n, q, arr[maxn], count = 0;
  10. while(scanf("%d %d", &n, &q) == 2 && n)
  11. {
  12. printf("CASE# %d:\n", ++count);
  13. for(int i = 0; i < n; i++)
  14. scanf("%d", &arr[i]);
  15. sort(arr, arr+n);
  16. while(q--)
  17. {
  18. int num; // 要搜尋的數
  19. scanf("%d", &num);
  20. int pos = lower_bound(arr, arr+n, num) - arr; // 用 lower_bound 查找 num 的位置
  21. if(arr[pos] == num)
  22. printf("%d found at %d\n", num, pos+1);
  23. else
  24. printf("%d not found\n", num);
  25. }
  26. }
  27. }

留言

這個網誌中的熱門文章

機率筆記 (1)

離散數學筆記 — vertex cut

機率筆記 (4) — 隨機變數