Fork me on GitHub

P2685抓牛(bfs)

题见洛谷

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<string>
#include<cmath>
#include<vector>
#define LL long long
#define p 0.00000001
using namespace std;
int n,k;
int pos[10000009];
int tim[10000009];
bool f[10000009];
int bfs()
{
    int head=0,tail=1;
    pos[1]=n;
    while(head<tail){
        head++;
        for(int i=1;i<=3;i++){
          int x;
          if(i==1) x=pos[head]+1;
          if(i==2) x=pos[head]-1;
          if(i==3) x=pos[head]*2;

          if(x>=0&&x<=100000&&!f[x]){
            pos[++tail]=x;
            f[x]=true;
            tim[pos[tail]]=tim[pos[head]]+1;
            if(pos[tail]==k) return tim[k];
          } 
        } 
    }
}
int main()
{
    //memset(f,false,sizeof(f));
    scanf("%d%d",&n,&k);
    if(n>=k){
        printf("%d",n-k);
        return 0;
    }
    else
    printf("%d",bfs());
    return 0;
}
posted @ 2017-02-06 11:43  primes  阅读(171)  评论(0编辑  收藏  举报