您的位置:首页 > 其它

POJ 3278 / hdu 2717 Catch That Cow (广搜)

2016-03-15 20:52 411 查看
POJ 3278

HDU 2717

广搜题,用一个数组标记就可以过,不标记的话会超内存。

另外,poj的数据要比hdu强一些,比如0 100,这种数据。不特判的话会RE。不过如果不特判,在poj上用C++提交也可以过,不太清楚为什么,难道C++对于负数的数组访问会优化?期待大神解答。。

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
int n, k;
int vis[100100];
struct node {
int pos, num;
};
void bfs() {
node x;
x.pos = n;
x.num = 0;
queue<node> q;
vis[x.pos] = 1;
q.push(x);
while(!q.empty()) {
node t = q.front();
q.pop();
if(t.pos == k) {
printf("%d\n", t.num);
return;
}
node tt;
tt.pos = t.pos + 1, tt.num = t.num + 1;
if(tt.pos <= 100000 && !vis[tt.pos]) {
vis[tt.pos] = 1;
q.push(tt);
}
if(t.pos > 0) { 	//排除小于零的情况
tt.pos = t.pos - 1, tt.num = t.num + 1;
if(tt.pos <= 100000 && !vis[tt.pos]) {
vis[tt.pos] = 1;
q.push(tt);
}
tt.pos = t.pos << 1, tt.num = t.num + 1;
if(tt.pos <= 100000 && !vis[tt.pos]) {
vis[tt.pos] = 1;
q.push(tt);
}
}
}
}
int main() {
while(~scanf("%d %d", &n, &k)) {
memset(vis, 0,sizeof(vis));
bfs();
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: