10474 - Where is the Marble? 有技巧地快速查找

原题

提供三个代码。效率由高到低。

当我认为二分的效率已经够高时,我看到了他的文章,又把效率提高了。链接

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
const int maxn=20000;

int be[maxn],pos[maxn];

int main()
{
#ifndef ONLINE_JUDGE
	freopen("10474.txt","r",stdin);
#endif
	int n,q,k=0;
	while(scanf("%d%d",&n,&q) && (n ||q))
	{
		printf("CASE# %d:\n",++k);	
		int i,j=0;
		memset(be,0,sizeof(be));
		for(i=0;i<n;i++) 
		{
			scanf("%d",&j);
			be[j]++;
		}
		j=0;
		for(i=0;i<10010;i++) if(be[i])
		{
			pos[i]=j+1;
			j+=be[i];
		}
		for(i=0;i<q;i++)
		{
			scanf("%d",&j);
			if(be[j])  printf("%d found at %d\n",j,pos[j]);
			else printf("%d not found\n",j);
		}
	}
	return 0;
}

#include<stdio.h>
#include<stdlib.h>
const int maxn=20000;

int A[maxn];

int cmp(const void *_a,const void *_b)
{
	int *a=(int *)_a;
	int *b=(int *)_b;
	return *a-*b;
}

int main()
{
	freopen("10474.txt","r",stdin);
	int n,q,k=0;
	while(scanf("%d%d",&n,&q) && (n ||q))
	{
		printf("CASE# %d:\n",++k);	
		int i;
		for(i=0;i<n;i++) scanf("%d",&A[i]);
		qsort(A,n,sizeof(A[0]),cmp);
		for(i=0;i<q;i++)
		{
			int t;
			scanf("%d",&t);
			int x=0,y=n-1;
			while(x<y)
			{
				int m=x+(y-x)/2;
				if(A[m]>=t)  y=m;
				else x=m+1;
			}
			if(A[x]==t) printf("%d found at %d\n",t,x+1);
			else printf("%d not found\n",t);
		}
		//for(i=0;i<n;i++) printf("%d\n",A[i]);
		//printf("\n");
	}
	return 0;
}

#include<stdio.h>
#include<stdlib.h>
const int maxn=20000;

int A[maxn];

int cmp(const void *_a,const void *_b)
{
	int *a=(int *)_a;
	int *b=(int *)_b;
	return *a-*b;
}

int main()
{
	freopen("10474.txt","r",stdin);
	int n,q,k=0;
	while(scanf("%d%d",&n,&q) && (n ||q))
	{
		printf("CASE# %d:\n",++k);	
		int i;
		for(i=0;i<n;i++) scanf("%d",&A[i]);
		qsort(A,n,sizeof(A[0]),cmp);
		for(i=0;i<q;i++)
		{
			int t;
			scanf("%d",&t);
			int *f=(int *)bsearch(&t,A,n,sizeof(A[0]),cmp);
			if(f==NULL) printf("%d not found\n",t);
			else 
			{	
				while(f!=0 && *(f-1)==*f ) f--;
				printf("%d found at %d\n",t,f-A+1);
			}
		}
		//for(i=0;i<n;i++) printf("%d\n",A[i]);
		//printf("\n");
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值