B2061 整数的个数 题解

· · 题解

题目传送门

对于这道题,我们可以使用 C++ STL 中的count()函数。

使用count()函数时,须引用algorithm头文件。它的参数是count(first,last,value)。其中first是容器的首迭代器,last是容器的末迭代器,value是询问的元素。它的功能是统计容器中等于value元素的个数。有关count()函数的更多知识,可以看这里和这里。

代码如下:

#include<iostream>
#include<algorithm>
using namespace std;
int k,a[101];
int main(){
    cin>>k;
    for(int i=1;i<=k;i++){
        cin>>a[i];
    }
    cout<<count(a+1,a+k+1,1)<<endl;//见下文
    cout<<count(a+1,a+k+1,5)<<endl;
    cout<<count(a+1,a+k+1,10);
    return 0;
}

同时,我们还可以使用 C++ STL 中的lower_bound()upper_bound函数。

lower_bound()upper_bound()都是利用二分查找的方法在一个排好序的数组中进行查找的,使用时须引用头文件algorithm

lower_bound()的参数是lower_bound(begin,end,value),作用是从begin位置到end-1位置二分查找第一个大于或等于value的数字,找到返回该数字的地址,不存在则返回end

upper_bound()的参数与lower_bound()的参数一模一样,但作用是从begin位置到end-1位置二分查找第一个大于value的数字,找到返回该数字的地址,不存在则返回end

要想求某个值出现的次数,只需将upper_bound()的结果减去lower_bound()的结果就可以了。

如果想要了解更多有关lower_bound()upper_bound()函数的知识,可以看看这篇文章。

注意:

测试数据不一定是有序的,所以要先排序。我使用的是sort()函数,如果还不熟悉,可以看看这篇和这篇文章。

代码如下:

#include<iostream>
#include<algorithm>
using namespace std;
int k,a[101];
int main(){
    cin>>k;
    for(int i=1;i<=k;i++){
        cin>>a[i];
    }
    sort(a+1,a+k+1);
    cout<<(upper_bound(a+1,a+k+1,1)-lower_bound(a+1,a+k+1,1))<<endl;//见下文
    cout<<(upper_bound(a+1,a+k+1,5)-lower_bound(a+1,a+k+1,5))<<endl;
    cout<<(upper_bound(a+1,a+k+1,10)-lower_bound(a+1,a+k+1,10));
    return 0;
}

Q:数组a的末位的下标明明是k,为什么末指针(即末迭代器)是a+k+1,而不是a+k?同理,为什么这样写不会出错吗?

A:实际上,a+k+1才是正确的写法。因为count()lower_bound()upper_bound()跟其他 STL 算法一样,其中的firstlast指针包含的区间是前闭后开的,不包括last指针所指向的元素。所以写成a+k还不够,应写成a+k+1