哈理工OJ 1316 移动 II (广度优先搜索+路径打印)

题目链接:http://acm.hrbust.edu.cn/index.php?m=ProblemSet&a=showProblem&problem_id=1316

移动 II
Time Limit: 1000 MS Memory Limit: 65536 K
Total Submit: 414(113 users) Total Accepted: 185(107 users) Rating: Special Judge: No
Description
在坐标轴[0,500]上存在两点A,B。

点A可以多次移动,每次移动需要遵循如下规则:

1.向后移动一步。

2.向前移动一步。

3.跳到当前坐标*2的位置上。

要求:利用宽搜算法编程求解从A移动到B的步数最少的方案,为使答案统一,要求搜索按照规则1、2、3的顺序进行。

Input
输入包含多组测试用例。

每组测试用例要求输入两个整数A,B。

Output
按要求输出步数最少的方案。

向后走输出”step back”。

向前走输出”step forward”。

跳跃输出”jump”。

对于每组结果需要追加一个空行。

Sample Input
5 17
5 18
3 499
Sample Output
step back
jump
jump
step forward

jump
step back
jump

step forward
jump
jump
jump
step back
jump
jump
step forward
jump
jump
step back
【题目分析】广度优先搜索找到最短路径,在找最短路径的同时把路径用数组记录下来,然后再把路径打印出来就好了。
【AC代码】

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
using namespace std;

int a[505],book[505],path[505];
int bfs(int s,int e)
{
    memset(book,0,sizeof(book));
    memset(path,-1,sizeof(path));
    queue<int>q;
    q.push(s);
    book[s]=1;
    while(!q.empty())
    {
        int fr=q.front();
        q.pop();
        if(fr==e)
        {
            return 1;
        }
        for(int i=1;i<=3;i++)
        {
            int j;
            if(i==1)
            {
                j=fr-1;
            }
            if(i==2)
            {
                j=fr+1;
            }
            if(i==3)
            {
                j=fr*2;
            }
            if(j>=0&&j<=500&&book[j]==0)
            {
                book[j]=1;
                path[j]=fr;
                q.push(j);
            }
        }
    }
    return -1;
}

int main()
{
    int m,n;
    while(~scanf("%d%d",&m,&n))
    {
        int sum=0;
        int u=n;
        int re=bfs(m,n);
        memset(a,0,sizeof(a));
        while(path[u]!=-1)
        {
           if(path[u]==u-1)
           {
               a[sum++]=1;//向前走
           }
           else if(path[u]==u+1)
           {
               a[sum++]=2;//向后走
           }
           else
           {
               a[sum++]=3;
           }
           u=path[u];
        }
        for(int i=sum-1;i>=0;i--)
        {
            if(a[i]==1)
            {
                printf("step forward\n");
            }
            else if(a[i]==2)
            {
                printf("step back\n");
            }
            else
            {
                printf("jump\n");
            }
        }
        printf("\n");
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值