poj 3728 Catch That Cow
基本的BFS搜索
1.记得每次都要清空队列,因为忘清空了卡了很久
2.hdu和poj上的数据输入方式是不一样的
#include<iostream>
#include<queue>
#include<cstdio>
#include<string.h>
using namespace std;
const int N = 1e5+5;
int vis[N], step[N];
queue <int> q;
int BFS(int n, int k){
int now, next;
vis[n] = 1; step[n] = 0;
q.push(n);
while(!q.empty()){
now = q.front();
q.pop();
for(int i=0; i<3; ++i){
if(i == 0) next = now - 1;
else if(i == 1) next = now + 1;
else if(i == 2) next = now * 2;
if(next < 0 || next > N) continue;
if(!vis[next]){
vis[next] = 1;
step[next] = step[now] + 1;
q.push(next);
}
if(next == k) return step[next];
}
}
}
int main(){
int n, k;
while(scanf("%d%d",&n,&k)!=EOF){
memset(vis, 0, sizeof(vis));
memset(step, 0, sizeof(step));
while(!q.empty()) q.pop();
printf("%d\n",BFS(n, k));
}
}
查看9道真题和解析