1024: 走路还是坐公交

#include <bits/stdc++.h>
using namespace std;
int n,k;
pair<int,int> pr;
const int N=200000;
bool vis[N];
int fun(int n,int k){
	int cnt=0;
	queue<pair<int,int>> que;
	que.push({n,cnt});
	vis[n]=1;
	while(!que.empty()){
		auto now=que.front();
		que.pop();
		if(now.first==k)
			return now.second;
		if(now.first>k){
			que.push({now.first-1,now.second+1});
		}else{
			if(vis[now.first+1]==0){
				vis[now.first+1]=1;
				que.push({now.first+1,now.second+1});
			}
			if(now.first-1>=0&&vis[now.first-1]==0){
				vis[now.first-1]=1;
				que.push({now.first-1,now.second+1});
			}
			if(vis[now.first*2]==0){
				vis[now.first*2]=1;
				que.push({now.first*2,now.second+1});
			}
		}	
	}
}
int main(){
	while(scanf("%d%d",&n,&k)!=EOF){
		if(k<n)
			{
			printf("%d\n",n-k);
			continue;}
		printf("%d\n",fun(n,k));
	}
}

错误:如果不在n>k的时候直接输出答案,而是使用bfs遍历,会超时50%。
改进,我可以把vis和dis合在一起,只用一个一维数组就可以了

#include <bits/stdc++.h>
using namespace std;
const int N=100010;
int vis[N*2];
int dist[N*2];
int bsf(int n,int k){
	queue <int> q;
	q.push(n);
	vis[n]=1;
	while(!q.empty()){
		auto now =q.front();
		q.pop();
		if(now==k)
			return dist[now];
		if(now+1<N&&!vis[now+1]){
			vis[now+1]=1;
			q.push(now+1);
			dist[now+1]=dist[now]+1;
		}
		if(now>=1&&!vis[now-1]){
			vis[now-1]=1;
			q.push(now-1);
			dist[now-1]=dist[now]+1;
		}
		if(now*2<N*2&&!vis[now*2]){
			vis[now*2]=1;
			q.push(now*2);
			dist[now*2]=dist[now]+1;
		}
	}
}
int main(){
	int n,k;
	while(scanf("%d%d",&n,&k)!=EOF){
		if(k<n){
			printf("%d\n",n-k);
			continue;
		} 
		memset(vis,0,sizeof(vis));
		memset(dist,0,sizeof(dist));
		printf("%d\n",bsf(n,k));
	}
}
posted @ 2026-02-11 01:02  peter_shen  阅读(9)  评论(0)    收藏  举报