poj3278Catch That Cow
题目大意及理解
农夫和奶牛在同一条坐标轴上,问农夫最少走几步可以到达奶牛所在的点
(抓到奶牛)农夫每步有3种走法:1.往前走一步 2,往后退一步 3.当前坐
标乘以2
ps:这题感觉不太能马上认出来是到广搜题目,然后在做的时候居然同时忘记
设置搜索边界和存储是否搜索结果,导致卡了好久。。
还有一个注意点:C++里面的this是指针需要用this->成员来调用成员,而Java直接代表
类,只需要用this.成员 就可以。
AC代码
# include <stdio.h>
# include <queue>
# include <string.h>
using namespace std;
int N, K;
int step = 0x3f3f3f3f;
bool vis[100005];
struct st {
int num, step;
st(int num, int step) {
this->num = num;
this->step = step;
}
st() {}
};
void bfs() {
queue<st> Q;
st temp(N, 0);
Q.push(temp);
while(!Q.empty()) {
st temp = Q.front();
Q.pop();
if(temp.num+1 == K) {
step = temp.step+1;
return;
}
if(temp.num-1 == K) {
step = temp.step+1;
return;
}
if(temp.num*2 == K) {
step = temp.step+1;
return;
}
st tmp(temp.num,temp.step+1);
tmp.num++;
if(tmp.num >= 0 && tmp.num < 100001 && !vis[tmp.num]) {
vis[tmp.num] = true;
Q.push(tmp);
}
tmp.num -= 2;
if(tmp.num >= 0 && tmp.num < 100001 && !vis[tmp.num]) {
vis[tmp.num] = true;
Q.push(tmp);
}
tmp.num = (tmp.num+1)*2;
if(tmp.num >= 0 && tmp.num < 100001 && !vis[tmp.num]) {
vis[tmp.num] = true;
Q.push(tmp);
}
}
}
int main() {
scanf("%d%d",&N,&K);
memset(vis,0,sizeof(vis));
if(N >= K) {
printf("%d\n",N-K);
return 0;
}
bfs();
printf("%d\n",step);
return 0;
}