抓住那头牛

本文深入探讨了使用队列和数组解决寻路问题的两种算法实现,通过对比分析,展示了如何在给定条件下找到从起点到终点的最短时间路径。涉及的关键概念包括节点结构、队列操作、数组标记以及时间复杂度优化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一开始觉得要比时间,结果本地就运行不出答案来,先搜到的用的时间一定少,不过还是很好奇为什么比时间运行不出答案来。原来是我的软件有问题,
在这里插入图片描述

#include<bits/stdc++.h>
using namespace std;
struct node{
	int x,time;
};
int a[100003];
int main()
{
	int n,k;
	cin>>n>>k;
	queue<node> q;
	q.push((node){n,0});
	memset(a,0,sizeof(a));
	int minn=1000000;
	while(!q.empty())
	{
		node t=q.front();
		q.pop();
		if(t.x==k)
		{
			minn=t.time;
			cout<<minn;
			return 0;
		}
		if(t.x-1>=0&&a[t.x-1]==0)
		 {
		 	q.push((node){t.x-1,t.time+1});
		 	a[t.x-1]=1;
		 }
		if(t.x+1<=100000&&a[t.x+1]==0)
		{
			q.push((node){t.x+1,t.time+1});
		 	a[t.x+1]=1;
		}
		if(2*t.x<=100000&&a[2*t.x]==0)
		{
			q.push((node){2*t.x,t.time+1});
		 	a[t.x*2]=1;
		}
		
	}
	cout<<minn<<endl;
	return 0;
}

用队列用的多了,这个题用数组也是可以的。

#include<bits/stdc++.h>
using namespace std;
int v[1000000],p[1000000],s[1000000],n,m,h,t=1;
int main()
{
     cin>>n>>m;
     v[n]=1,p[t]=n;
     while(h<t)
     {
        h++;
        int x=p[h];
        if(x==m)
        {
                cout<<s[h]<<endl;return 0;
         }
         if(v[x-1]==0&&x-1>=0)
              t++,p[t]=x-1,s[t]=s[h]+1,v[x-1]=1;
            if(v[x+1]==0&&x+1<=100000)
                 t++,p[t]=x+1,s[t]=s[h]+1,v[x+1]=1;
            if(v[2*x]==0&&2*x<=100000)
                t++,p[t]=2*x,s[t]=s[h]+1,v[2*x]=1;
      } 
   return 0;
} 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值