1 条题解
-
0
自动搬运
来自洛谷,原作者为

一只大龙猫
嗷~呜!搬运于
2025-08-24 21:03:07,当前版本为作者最后更新于2021-07-26 11:49:04,作者可能在搬运后再次修改,您可在原文处查看最新版自动搬运只会搬运当前题目点赞数最高的题解,您可前往洛谷题解查看更多
以下是正文
对于这道题,我们可以使用 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 算法一样,其中的first和last指针包含的区间是前闭后开的,不包括last指针所指向的元素。所以写成a+k还不够,应写成a+k+1。
- 1
信息
- ID
- 6918
- 时间
- 1000ms
- 内存
- 512MiB
- 难度
- 1
- 标签
- 递交数
- 1
- 已通过
- 1
- 上传者