kuangbin.Catch That Cow(dfs+bfs)

刚一碰见这道题,我真是傻乎乎的用dfs做,不过我是真的做不出来,后来想了想,一旦入栈,这出来了的时候估计我骨灰都进二向箔了,至少我目前没想到加什么条件可以解决。把你骗进来了不好意思。

#include<bits/stdc++.h>
using namespace std;

int n,k,res;

int dfs(int x){
	if(x<0||x>100000){
		return 0;
	}
	if(x==k){
		res=0;
	}
	else if(x<k){
		res=min(dfs(x+1)+1,min(dfs(x*2)+1,dfs(x-1)+1));
	}
	else{
		res=dfs(x-1)+1;
	}
	return res;
}

int main(){
	ios::sync_with_stdio(false);
	cin.tie(0);
	cin>>n>>k;
	cout<<dfs(n);
	return 0;
}

bfs:(每个点第一次入队的时间一定是最短时间,所以每个点一旦入队,后面再遇到这个点就不用再次入队了,细品)

#include<bits/stdc++.h>
using namespace std;

int arr[100010];
queue<int> que;

int main(){
	ios::sync_with_stdio(false);
	cin.tie(0);
	int t,n,k;
	cin>>t;
	for(int i=1;i<=t;i++){
		cin>>n>>k;
		que.push(n);
		while(!que.empty()){
			int t=que.front();
			que.pop();
			if(t+1>=0&&t+1<=100000&&arr[t+1]==0){
				que.push(t+1);
				arr[t+1]=arr[t]+1;
			}
			if(t*2>=0&&t*2<=100000&&arr[t*2]==0){
				que.push(t*2);
				arr[t*2]=arr[t]+1;
			}
			if(t-1>=0&&t-1<=100000&&arr[t-1]==0){
				que.push(t-1);
				arr[t-1]=arr[t]+1;
			}
		}
		cout<<arr[k]<<endl;
		while(!que.empty()){
			que.pop();
		}
		memset(arr,0,sizeof(arr));
	}
	return 0;
}

如果想在快点,加个特判,如果遇到牛立马输出,break;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值