bfs+路径记录

来源:互联网 发布:亨利领 t恤 知乎 编辑:程序博客网 时间:2024/06/07 04:35
移动 IITime Limit: 1000 MSMemory Limit: 65536 KTotal Submit: 324(85 users)Total Accepted: 144(78 users)Rating: Special Judge: NoDescription

在坐标轴[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 175 183 499
Sample Output
step backjumpjumpstep forwardjumpstep backjumpstep forwardjumpjumpjumpstep backjumpjumpstep forwardjumpjumpstep back
Source2012 Spring Contest 4 - Search TechnologyAuthor这是一道bfs的题目,只需要加一个路径记录就可以了
#include<cstdio>#include<iostream>#include<algorithm>#include<queue>#include<vector>#include<string.h>#include<set>#include<stack>#define nn 120005#define INF 0x7FFFFFFusing namespace std;int use[nn];int step[nn];int id[nn];struct node{    int x;};void bfs(int a,int b){    int i,j;    queue<node> que;    node now,then;    now.x=a;    que.push(now);   //5 id[a]=a;    use[a]=1;    while(!que.empty())    {        then=que.front();        que.pop();        if(then.x==b)        {            return ;        }       if(use[then.x-1]==0&&(then.x-1)>=0&&(then.x-1)<=700 )        {            now.x=then.x-1;            step[now.x]=-1;            id[now.x]=then.x;            use[now.x]=1;            que.push(now);        }        if(use[then.x+1]==0&&(then.x+1)>=0&&(then.x+1)<=700)        {            step[then.x+1]=1;            now.x=then.x+1;            id[now.x]=then.x;            use[now.x]=1;            que.push(now);        }        if(use[then.x*2]==0&&then.x*2>=0&&then.x*2<=700)        {             now.x=then.x*2;            step[now.x]=2;            id[now.x]=then.x;            use[now.x]=1;            que.push(now);        }    }}int main(){   int i,j;   int a,b;   while(scanf("%d %d",&a,&b)!=EOF)   {       if(a==b)       {           printf("\n");           continue;       }        stack<int> bow;        memset(use,0,sizeof(use));        memset(step,0,sizeof(step));        memset(id,-1,sizeof(id));        bfs(a,b);        int mm=b;        while(1)        {            bow.push(step[mm]);            mm=id[mm];            if(id[mm]==-1)              break;        }        int ff;        while(!bow.empty())        {            ff=bow.top();            bow.pop();            if(ff==1)               printf("step forward\n");            else if(ff==-1)               printf("step back\n");            else if(ff==2)               printf("jump\n");     }     printf("\n");   }}
0 0
原创粉丝点击