poj 3278 Catch That Cow
原创
©著作权归作者所有:来自51CTO博客作者Nemaleswang的原创作品,请联系作者获取转载授权,否则将追究法律责任
题目链接:Catch That Cow
题目大意:给你一个起点,一个终点,一共有三种操作,向前走一步,向后走一步,前进到当前位置两倍的位置,问最少需要多少步从起点到终点
题目思路:直接bfs就好,特判一下越界的情况
#include <stdio.h>
#include <iostream>
#include <algorithm>
#include <queue>
#include <string.h>
using namespace std;
const int maxn = 1e5+1;
int step[maxn];
bool vis[maxn];
queue<int>q;
int bfs(int n,int k){
int head,next;
q.push(n);
vis[n] = true;
step[n] = 0;
while(!q.empty()){
head = q.front();
q.pop();
for(int i = 0;i < 3;i++){
if(i == 0) next = head-1;
else if(i == 1) next = head*2;
else next = head+1;
if(next < 0||next >= maxn) continue;
if(!vis[next]){
vis[next] = true;
step[next] = step[head]+1;
q.push(next);
}
if(next == k) return step[next];
}
}
return -1;
}
int main(){
int n,k;
while(~scanf("%d%d",&n,&k)){
memset(step,0,sizeof(step));
memset(vis,0,sizeof(vis));
while(!q.empty()) q.pop();
if(n >= k) printf("%d\n",n-k);
else printf("%d\n",bfs(n,k));
}
return 0;
}