一开始觉得要比时间,结果本地就运行不出答案来,先搜到的用的时间一定少,不过还是很好奇为什么比时间运行不出答案来。原来是我的软件有问题,
#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;
}