UVA - 10474 - Where is the Marble

8 篇文章 0 订阅

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_TEST

const int MAXN = 100002;

int main()
{
#ifdef LOCAL_TEST
	freopen("f:\\in.txt", "r", stdin);
	freopen("f:\\out.txt", "w+", stdout);
#endif
	int 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';
			else
				cout <<tmpIn <<" not found" <<'\n';
		} // end for
	} // end while

	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值