[codeforces 1293A] ConneR and the A.R.C. Markland-N 不超时的二分/无限长数组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

方法一:不超时的二分

Problem Lang Verdict Time Memory
A - ConneR and the A.R.C. Markland-N GNU C++11 Accepted 31 ms 0 KB

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

#include 
#include 
#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+1x)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+桶排序

Problem Lang Verdict Time Memory
A - ConneR and the A.R.C. Markland-N GNU C++11 Accepted 31 ms 0 KB

 

#include 
#include 
#define N 1010
using namespace std;
int a,k;
int main(){
	int t,n,s,i,j,step;
	scanf("%d",&t);
	while(t--){
		map 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;
}

 

你可能感兴趣的:(codeforces)