[codeforces 1293A] ConneR and the A.R.C. Markland-N 不超时的二分/无限长数组map+桶排序

本文提供Codeforces 1293A题目“ConneRand the A.R.C. Markland”两种解题思路:一是优化的二分查找算法,避免超时;二是利用map和桶排序处理无限长数组,实现快速查找。通过具体代码示例,展示如何在给定限制内高效解决问题。

[codeforces 1293A] ConneR and the A.R.C. Markland-N 不超时的二分/无限长数组map+桶排序

总目录详见https://blog.csdn.net/mrcrack/article/details/103564004

在线测评地址https://codeforces.com/contest/1293/problem/A

方法一:不超时的二分

ProblemLangVerdictTimeMemory
A - ConneR and the A.R.C. Markland-N GNU C++11Accepted31 ms0 KB

//想不到,写了二分,写得不好,还会超时

#include <cstdio>
#include <algorithm>
#define N 1010
using namespace std;
int a[N],k;
int bisection(int x){//返回1找到,返回0没找到
	int left=0,right=k+1,mid;
	while(left+1<right){
		mid=(left+right)/2;
		if(a[mid]<x)left=mid;
		else if(a[mid]>x)right=mid;
		else if(a[mid]==x)return 1;//此句关键,及时结束二分搜索,也是不超时的关键所在。
	}
	return 0;
}
int main(){
	int t,n,s,i,j,step;
	scanf("%d",&t);
	while(t--){
		scanf("%d%d%d",&n,&s,&k);
		step=0;
		for(i=1;i<=k;i++)scanf("%d",&a[i]);
		a[0]=a[k+1]=0;
		sort(a+1,a+1+k);
		while(1){
			if(s+step<=n&&bisection(s+step)==0)break;
			else if(s-step>0&&bisection(s-step)==0)break;
			step++;
		}
		printf("%d\n",step);
	}
	return 0;
}

方法二:无限长数组map+桶排序

ProblemLangVerdictTimeMemory
A - ConneR and the A.R.C. Markland-N GNU C++11Accepted31 ms0 KB

 

#include <cstdio>
#include <map>
#define N 1010
using namespace std;
int a,k;
int main(){
	int t,n,s,i,j,step;
	scanf("%d",&t);
	while(t--){
		map<int,int> used;
		scanf("%d%d%d",&n,&s,&k);
		step=0;
		for(i=1;i<=k;i++)scanf("%d",&a),used[a]=1;
		while(1){
			if(s+step<=n&&used[s+step]==0)break;
			else if(s-step>0&&used[s-step]==0)break;
			step++;
		}
		printf("%d\n",step);
	}
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值