D - Where is the Marble?
https://vjudge.net/contest/416664#problem/D
要点:STL中的 lower_bound 运用
lower_bound:查找第一个大于或等于某个元素的位置。
a.函数模板:lower_bound(arr[],arr[]+size , indx):
b.参数说明:
arr[]: 数组首地址
size:数组元素个数
indx:需要查找的值
c.函数功能: 函数lower_bound()在first和last中的前闭后开区间进行二分查找,返回大于或等于val的第一个元素位置(注意是地址)。如果所有元素都小于val,则返回last的位置
方法一:
1 #include <iostream> 2 #include <cstdio> 3 #include <algorithm> 4 using namespace std; 5 int arr[1000000]; 6 int main() 7 { 8 int n,q; 9 int case_=0; 10 int last=0; 11 while (cin>>n>>q&&n&&q) 12 { 13 case_++; 14 for(int i=0;i<n;i++) 15 cin>>arr[i]; 16 sort(arr,arr+n); 17 for (int i = 0; i < q; ++i) 18 { 19 int tmp,index; 20 cin>>tmp; 21 for (int j = 0; j<n ; ++j) 22 { 23 if(arr[j]==tmp) 24 { 25 index=j; 26 break; 27 } else 28 index=-1; 29 } 30 if(last!=case_) 31 cout<<"CASE# "<<case_<<':'<<endl; 32 last=case_; 33 if(index!=-1) 34 cout<<tmp<<" found at "<< index+1<<endl; 35 else 36 cout<<tmp<<" not found"<<endl; 37 } 38 } 39 return 0; 40 }
方法二:
1 #include <iostream> 2 #include <algorithm> 3 using namespace std; 4 const int MAXN=1e4+20; 5 int arr[MAXN]; 6 7 int main() 8 { 9 int n,q,kase=1; 10 while (cin>>n>>q&&(n||q)) 11 { 12 for (int i = 0; i < n; ++i) 13 { 14 cin>>arr[i]; 15 } 16 sort(arr,arr+n); 17 cout<<"CASE# "<<kase++<<":"<<endl; 18 while (q--) 19 { 20 int num; 21 cin>>num; 22 int pos=lower_bound(arr,arr+n,num)-arr; 23 if(arr[pos]==num) 24 { 25 cout<<num<<" found at "<<pos+1<<endl; 26 } else 27 { 28 cout<<num<<" not found"<<endl; 29 } 30 } 31 } 32 return 0; 33 }

浙公网安备 33010602011771号