您的位置:首页 > 其它

搜索-BFS-poj3278

2016-08-22 17:33 211 查看
题意:

给定 两个坐标X ,Y 

给定三个操作 1: 2*x

 2:  x-1;

3: x+1;

找到最少变换的步骤可以将X变为Y;

思路:

一开始以为是个思维题。但是写半天发现不是。时间1S,数据量不大,广搜过了! 

搜索从一点到另外三点。通过给定的三种步骤。#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <queue>
#include <cstring>
using namespace std;
int n,m;
bool go[200011];
int step[200011];
void bfs()
{ queue <int > a;

if(n==m)
printf("0\n");
a.push(n);
go
=true;
step
=0;
int temp;
while(!a.empty())
{
int tep=a.front();
a.pop();
for(int i=1;i<=3;i++)
{
if(i==1)
{
temp=tep*2;

}
else if(i==2)
{
temp=tep-1;
}
else{
temp=tep+1;
}
if(temp<0||temp>100000)//注意这一步必须有,否则数字会无限大做下去。
continue;
if(go[temp]!=true)//这步骤优化可以保证所有都是在N个数字里循环
{
step[temp]=step[tep]+1;
a.push(temp);
if(temp==m)
{
printf("%d\n",step[temp]);
return ;
}
go[temp]=true;
}
}
}
}
int main()
{int flag=0;
while(scanf("%d%d",&n,&m)!=EOF)
{
memset(go,0,sizeof(go));
memset(step,0,sizeof(step));
bfs();
}

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