算法入门经典:大理石在哪儿
来源:互联网 发布:java源码分析书籍 编辑:程序博客网 时间:2024/04/30 09:21
大理石在哪儿(where is the marble? , UVa 10474)
前言:好好努力,在研一参加一次关于ACM竞赛,完成本科的期望。
问题:
现有N个大理石,每个大理石上写了一个非负整数、首先把各数从小到大排序;然后回答Q个问题。每个问题问是否有一个大理石写着某个整数x,如果是,还要回答哪个大理石上写着x。排序后的大理石从左到右编号为1~N。
(在样例中,为了节约篇幅,所有大理石的数合并到一行,所有问题也合并到一行。)
样例输入:
4 1
2 3 5 1
5
5 2
1 3 3 3 1
2 3
样例输出:
CASE# 1:
5 found at 4
CASE# 2:
2 not found
4 1
2 3 5 1
5
5 2
1 3 3 3 1
2 3
样例输出:
CASE# 1:
5 found at 4
CASE# 2:
2 not found
3 found at 3
代码:
//大理石在哪#include <cstdio>#include <algorithm>using namespace std;const int maxn = 10000;int main(){int num, ques, x, a[maxn], kase = 0;while(scanf("%d%d", &num, &ques) == 2 && num){printf("CASE# %d:\n", ++kase);for(int i = 0; i < num; i++)scanf("%d", &a[i]);sort(a, a+num); //排序while(ques --){scanf("%d", &x);int p = lower_bound(a, a+num, x) - a; //在已排序数组a中找xif(a[p] == x)printf("%d found at %d\n", x, p+1);elseprintf("%d not found\n", x);}}return 0;}
总结:
主要学习了STL,然后就是 lower_bound( ) ;
int p = lower_bound(a, a+num, x) - a;这段代码让我思考好一会,主要是因为忘了a是一个数组,lower_bound( )返回的是一个迭代器,-a相当于减去a的首地址,返回的p即是它们之间的距离。
关于此函数的拓展使用:
一个数组number序列为:4,10,11,30,69,70,96,100.设要插入数字3,9,111.pos为要插入的位置的下标则(注:number为数组名)
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,所以返回最后一个元素的下一个元素)。
阅读全文
1 0
- 算法入门经典:大理石在哪儿
- 《算法竞赛入门经典2ndEdition 》例题5-1 大理石在哪儿(Where is the marble?, Uva10474)
- 大理石在哪儿
- UVa 10474 大理石在哪儿
- STL初步:大理石在哪儿?
- C++之大理石在哪儿?
- 例题:大理石在哪儿(UVa 10474)
- 算法之路二:刘汝佳算法竞赛入门经典:STL排序与检索 大理石在哪 UVA10474
- uva10474大理石在哪儿where is the marble?
- 大理石在哪儿?(Stl lower_bound用法)
- 例题5-1 大理石在哪儿 UVa10474
- 大理石在哪儿 where is the Marble? lower_bound()
- 大理石在哪儿 (排序和查找) UVA
- 大理石在哪儿 where is the Marble?
- UVa 10474 Where is the Marble?(大理石在哪儿)
- 大理石在哪儿(UVa 10474)(排序与检索)
- 10474 - 大理石在哪儿Where is the Marble?(排序+检索)
- uva 10474 Where is the Marble?(大理石在哪儿)
- HDU 6053 TrickGCD(枚举)
- css如何实现数字在图标上显示
- 124_容器_内置类比较_Comparable_排序工具类实现
- [SMOJ2100]打印机
- 125_容器_内置类比较_Comparator_排序工具类实现
- 算法入门经典:大理石在哪儿
- 126_容器_自定义数据排序
- Linux实施抢占补丁的研究与实践
- 有道词典在谷歌Chrome浏览器中无法取词的解决方法
- HDU-3954:Level up(特殊的线段树成段更新)
- 127_容器_排序容器_TreeSet与TreeMap
- 关于JSON与ajax操作
- PHP后台支付的开发:微信支付和支付宝支付
- web components简介