UVA - 10474 - Where is the Marble

来源:互联网 发布:雷诺数据 编辑:程序博客网 时间:2024/05/06 18:37

http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=98&page=show_problem&problem=1415


题意:

    猜数字游戏。输入目标数字表,乱序;接着再输入猜数字,找到则输出位置(数字表正序第一个出现的位置),否则输出找不到。

解题:

    用数组保存数字,再用sort排序;再用二分查找binary_search,输出第一个位置使用lower_bound。

    注:优先使用stl::sort > c::qsort;二分查找快,有现成算法用;lower_bound直接输出第一个出现位置,注意返回值的是指针位置,要转换后再输出。

    一开始定义数组长度为1002还RE,开到10002就过。

    看了别人的题解,果然有很多新知识,不能一味刷AC,要借鉴学习新知识点!

    别滥用花括号,简洁也一样可视化。


#include <iostream>#include <algorithm>#include <stdio.h>#include <string.h>using namespace std;// #define LOCAL_TESTconst int MAXN = 100002;int main(){#ifdef LOCAL_TESTfreopen("f:\\in.txt", "r", stdin);freopen("f:\\out.txt", "w+", stdout);#endifint n, q;int num[MAXN];int tmpIn;int nCase = 0;while ( cin >>n >> q ){if ( n == 0 && q == 0 )break;nCase++;memset(num, 0, sizeof(num));for ( int i=0; i<n; i++ )cin >>num[i];sort(num, num+n);cout <<"CASE# " <<nCase <<":" <<'\n';for ( int i=0; i<q; i++ ){cin >>tmpIn;if ( binary_search(num, num+n, tmpIn) )cout <<tmpIn <<" found at " <<lower_bound(num, num+n, tmpIn)-num+1 <<'\n';elsecout <<tmpIn <<" not found" <<'\n';} // end for} // end whilereturn 0;}


0 0
原创粉丝点击