题意是让你从N位置去抓K位置的牛牛~注意N,K大小不能确定~,你可以有三种走法,n+1或n-1或n*2。
第一次想到求最短路,用bfs,用的不够灵活,代码很幼稚,活生生的TLE。
TLE代码:
#include<stdio.h>
#include<queue>
using namespace std;
struct point
{
int x;
int step;
};
int bfs(int s,int e)
{
queue<point> Q;
point now,next;
now.x=s;
now.step=0;
Q.push(now);
while(!Q.empty())
{
now=Q.front();
Q.pop();
for(int i=0; i<3; i++)
{
if(i==0)
next.x=now.x+1;
else if(i==1)
{
if(now.x==1)
continue;
next.x=now.x-1;
}
else if(i==2)
{
if(now.x==0)
continue;
next.x=now.x*2;
}
if(next.x==-1||next.x==100001)
continue;
else if(next.x==e)
{
//printf(" %d\n",next.x);
return now.step+1;
}
else
{
next.step=now.step+1;
//vis[next.x]=1;
Q.push(next);
// printf(" %d\n",next.x);
}
}
}
}
int main()
{
int star,end;
while(scanf("%d%d",&star,&end)!=EOF)
{
printf("%d\n",bfs(star,end));
}
return 0;
}
第二次参考了别人的家的孩子,加了剪枝,飙泪过关。
时间和空间用的比较多。4744K,313MS
代码:
#include<stdio.h>
#include<string.h>
#include<queue>
using namespace std;
int step[1000001];
int bfs(int s,int e)
{
queue<int> Q;
int now;
now=s;
step[now]=1;
Q.push(now);
while(!Q.empty())
{
now=Q.front();
Q.pop();
if(now==e)
return step[now]-1;
if(now>=2&&step[now-1]==0) //-1
{
step[now-1]=step[now]+1;
Q.push(now-1);
}
if(now<=999999&&step[now+1]==0) //+1
{
step[now+1]=step[now]+1;
Q.push(now+1);
}
if(now<=500000&&step[2*now]==0) //*2
{
step[2*now]=step[now]+1;
Q.push(2*now);
}
}
}
int main()
{
int star,end;
while(scanf("%d%d",&star,&end)!=EOF)
{
if(star>end)
printf("%d",star-end);
else
{
memset(step,0,sizeof(step));
printf("%d\n",bfs(star,end));
}
}
return 0;
}