catch the cow bfs

题目链接

http://acm.hdu.edu.cn/showproblem.php?pid=2717

#include<iostream> 
#include<stack>
#include<queue>
#include<cstring>
#define maxn 1000005
using namespace std;
int a[maxn]={0};
int check(int n)//标记
{
    if(n<0||n>maxn-5||a[n])
    return false;
    return true;
}
void bfs(int n,int m)
{
    queue<int> b;
    b.push(n);
    while(b.size())
    {
        int k=b.front();
         b.pop();
         if(k==m)
         break;
         if(check(k-1))
         {
             b.push(k-1);
             a[k-1]=a[k]+1; //记录路径   
         }
          if(check(k+1))
         {
             b.push(k+1);
             a[k+1]=a[k]+1;    
         }
          if(check(k*2))
         {
             b.push(k*2);
             a[k*2]=a[k]+1;    
         }
    }
    
}
int main()
{
    int n,m;
    while(cin>>n>>m)
    {
    memset(a,0,sizeof(a));
    bfs(n,m);
    cout<<a[m]<<endl;
    }
    return 0;
}

其实bfs可以写

关键的是怎么求路径etc

参考https://www.cnblogs.com/xujunming/p/6734704.html

猜你喜欢

转载自www.cnblogs.com/liuzhaojun/p/10761586.html