搜索-BFS-poj3278

来源:互联网 发布:windows一键web安装包 编辑:程序博客网 时间:2024/06/05 22:36

题意:

给定 两个坐标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[n]=true;    step[n]=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();    }}

0 0
原创粉丝点击