UVa 10474 - Where is the Marble?【排序和检索】

原题网址:

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



思路,先排序,然后二分搜索不小于某个值的那个数的位置,如果这个位置和这个数相等,那么就找到了,否则没有,对应输出结果!

个人推荐 用lower_bound函数,个人习惯自己构造二分函数了......


#include<stdio.h>
#include<algorithm>
using namespace std;
int n,m,x[10005],k=0;
int search(int s)//二分
{
	int l=0,r=n;
	while(l<r)
	{
		int mid=(l+r)>>1;
		/*if(x[mid]==s)
		{
			return mid;
		}*/
		if(x[mid]>=s)
		{
			r=mid;
		}
		else
		{
			l=mid+1;
		}
	}
	return r;//这个是第一个不小于指定的数的下标
}
void slove()
{
	sort(x,x+n);
	printf("CASE# %d:\n",++k);
	for(int i=0;i<m;++i)
	{
		int tp,p;
		scanf("%d",&tp);
		p=search(tp);
		if(x[p]==tp)
		{
			printf("%d found at %d\n",tp,p+1);
		}
		else
		{
			printf("%d not found\n",tp);
		}
	}
}
int main()
{
	//freopen("shuju.txt","r",stdin);
	while(scanf("%d%d",&n,&m),n|m)
	{
		for(int i=0;i<n;++i)
		{
			scanf("%d",x+i);
		}
		slove();
	}
	return 0;
}


因为自己的变量重复定义了,导致程序一直运行错误,纠结了好一会,一段时间不敲代码,还真是忘了,被低级错误困扰....好好学习吧!



你可能感兴趣的:(UVa 10474 - Where is the Marble?【排序和检索】)