pku 3278 Catch That Cow---BFS

poj 3278(bfs)
题目很简单,bfs直接可以解决掉,注意截枝:有些位置前面已经出现了,后面就不用重复了。
设了一个tag[]帮助解决这个问题。
#include<algorithm>
#include<iostream>
#include<stdio.h>
#include <queue>
#define Len 100005
using namespace std;

struct Node
{
     int x;
  int step;
};
bool tag[Len];
int main()
{
 queue<Node> q;
 int n,k,x,step,ans;
 Node cur;
 scanf("%d%d",&n,&k);
 
  ans=0;
  memset(tag,0,sizeof(tag));
  cur.x=n;
  cur.step=0;
  tag[n]=1;
  q.push(cur);

  while(!tag[k])//bfs
  {

   cur=q.front();
   q.pop();
   x=cur.x;
   step=cur.step;
   if(x-1>=0&&!tag[x-1])//截枝,是否超出界限?前面是否访问过此点?
   {
    
    tag[x-1]=1;
    cur.x=x-1;
    cur.step=step+1;//前一步的时间+1,
    q.push(cur);
    if(x-1==k)
    {
     ans=step+1;
     break;
    }
   }
   if(x+1<Len&&!tag[x+1])
   {
    tag[x+1]=1;
    cur.x=x+1;
    cur.step=step+1;
    q.push(cur);
    if(x+1==k)
    {
     ans=step+1;
     break;
    }
   }
   if(x*2<Len&&!tag[x*2])
   {
    tag[x*2]=1;
    cur.x=2*x;
    cur.step=step+1;
    q.push(cur);
    if(2*x==k)
    {
     ans=step+1;
     break;
    }
   }
  }
 printf("%d/n",ans);
  
 

return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值