POJ-3278 Catch That Cow
题目链接:POJ-3278
题目大意:农夫再n这个点上找在k点的牛 农夫可以步行 可以向前走一步或者向后走一步 可以传送 传送到2*当前节点的位置上 问农夫多少步可以找到牛
解题思路:BFS 以为贼简单的那种 然后就错了两次
第一次内存超限 肯定是queue爆掉了 然后我就把queue提升到方法外边了 还是超限
然后试了试1 100000这组数据 发现根本出不来结果 然后意识到假如1到2 2还会到1 这样一直生成下去会很占用空间
然后弄了个标识组 已经取过的地方不再走过 就过了
后面那些queueA.front比较乱 下次取出来用就好了
代码块:
#include<iostream>
#include<queue>
using namespace std;
int n,k,sum;
typedef pair<int, int> p;// 当前位置和当前步数
queue<p> queueA;
bool arrA[100005];
void bfs(int x, int step);
int main(){
cin>>n>>k;
arrA[n] = true;
bfs(n,0);
cout<<sum;
return 0;
}
void bfs(int x, int step){
queueA.push(p(x,0));
while(queueA.size()){
if(queueA.front().first == k){
sum = queueA.front().second;
break;
}
// 向前走
if(queueA.front().first < 100000 && !arrA[queueA.front().first + 1]){
queueA.push( p(queueA.front().first + 1,queueA.front().second + 1) );
arrA[queueA.front().first + 1] = true;
}
// 向后走
if(queueA.front().first > 0 && !arrA[queueA.front().first - 1]){
queueA.push( p(queueA.front().first - 1,queueA.front().second + 1) );
arrA[queueA.front().first - 1] = true;
}
// 传送
if(queueA.front().first * 2 <= 100000 && !arrA[queueA.front().first * 2]){
queueA.push( p(queueA.front().first * 2, queueA.front().second + 1) );
arrA[queueA.front().first * 2] = true;
}
queueA.pop();
}
}