題目大意:在一個座標軸上。有一個農夫準備追牛。可以向前,向後,也可以座標加倍。求最少幾步可以追上牛。
思路:求最短時間,應該使用bfs,使用sign標記這個點是否走過。bfs有三個方向,最後輸出步數即可
#include<stdio.h>
#include<string.h>
struct node
{
int s;
int stage;
}queue[100005];//隊列
int sign[100005];
int check(int k){//判斷這個點能否走
if(k>=0&&k<=100000&&!sign[k])
return 1;
return 0;
}
int main()
{
int n,k;
while(scanf("%d%d",&n,&k)!=EOF)
{
memset(sign,0,sizeof(sign));//初始化
int head=0,tail=1;
struct node r;
sign[n]=1;
queue[head].s=n;
queue[head].stage=0;//起點
// printf("%d %d\n",tail,head);
while(head<tail)
{
r=queue[head];
int temp;
temp=r.s+1; //前進一步
if(check(temp))
{
queue[tail].stage=r.stage+1;
queue[tail].s=temp;
sign[temp]=1;
if(queue[tail].s==k)//判斷是否到達終點
break;
tail++;
// printf("%d %d\n",tail,head);
}
temp=r.s-1;//後退一步
if(check(temp))
{
queue[tail].stage=r.stage+1;
queue[tail].s=temp;
sign[temp]=1;
if(queue[tail].s==k)
break;
tail++;
}
temp=r.s*2;//步數×2
if(check(temp))
{
queue[tail].stage=r.stage+1;
queue[tail].s=temp;
sign[temp]=1;
if(queue[tail].s==k)
break;
tail++;
}
head++;
}
int i;
//for(i=0;i<10;i++)
printf("%d\n",queue[tail].stage);//輸出最短步數
}
return 0;
}