UVA - 10474

第五章的第一個大理石的題,附上書上的代碼
#include<cstdio>
#include<algorithm>
using namespace std;
const int maxn=10000;
int main()
{
    int n,q,x,a[maxn],kase=0;
    while(scanf("%d%d",&n,&q)==2&&n)
    {
        printf("CASE# %d:\n",++kase);
        for(int i=0;i<n;i++)
            scanf("%d",&a[i]);
        sort(a,a+n);
        while(q--)
        {
            scanf("%d",&x);
            int p=lower_bound(a,a+n,x)-a;
            if(a[p]==x)printf("%d found at %d\n",x,p+1);
            else printf("%d not found\n",x);
        }
    }
    return 0;
}
這個題裏面有一個stl函數 lower_bound,這個函數參數爲(數組起始位置,數組終止位置,所需要尋找的數x)—數組名,

函數lower_bound()在first和last中的前閉後開區間進行二分查找,返回大於或等於val的第一個元素位置。如果所有元素都小於val,則返回last的位置

舉例如下:

一個數組number序列爲:4,10,11,30,69,70,96,100.設要插入數字3,9,111.pos爲要插入的位置的下標

pos = lower_bound( number, number + 8, 3) - number,pos = 0.即number數組的下標爲0的位置。

pos = lower_bound( number, number + 8, 9) - number, pos = 1,即number數組的下標爲1的位置(即10所在的位置)。

pos = lower_bound( number, number + 8, 111) - number, pos = 8,即number數組的下標爲8的位置(但下標上限爲7,所以返回最後一個元素的下一個元素)。

所以,要記住:函數lower_bound()在first和last中的前閉後開區間進行二分查找,返回大於或等於val的第一個元素位置。如果所有元素都小於val,則返回last的位置,且last的位置是越界的!!~

返回查找元素的第一個可安插位置,也就是“元素值>=查找值”的第一個元素的位置


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章