您的位置:首页 > 其它

bfs+路径记录

2015-05-16 23:16 176 查看
移动
II
Time
Limit: 1000 MS
Memory Limit: 65536 K
Total
Submit: 324(85 users)
Total Accepted: 144(78 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
Source
2012
Spring Contest 4 - Search Technology
Author
这是一道bfs的题目,只需要加一个路径记录就可以了


#include<cstdio>
#include<iostream>
#include<algorithm>
#include<queue>
#include<vector>
#include<string.h>
#include<set>
#include<stack>
#define nn 120005
#define INF 0x7FFFFFF
using 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");
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: