hdu 2717 Catch That Cow bfs

来源:互联网 发布:编程适合高中生吗 编辑:程序博客网 时间:2024/05/03 05:59

http://acm.hdu.edu.cn/showproblem.php?pid=2717

抓一群静止的牛,并且每次移动的方式只有x+1,x-1,2*x,主要要控制数据范围,不然漫无目的的广搜会超内存的。

参考代码:

#include <cstdio>#include <iostream>#include <queue>using namespace std;#define MAX 200001bool used[MAX];int n, k;typedef struct _node {int step;int tmp;bool operator <(const struct _node &a)const{return a.step < step;}}node;priority_queue<node >q;void bfs(){node tp, tm;while(!q.empty()){tp = q.top();q.pop();if(tp.tmp == n){printf("%d\n", tp.step);break;}used[tp.tmp] = true;tm.step = tp.step + 1;if(tp.tmp + 1 <= k * 2 && !used[tp.tmp + 1]){tm.tmp = tp.tmp + 1;q.push(tm);}if(tp.tmp - 1 >= n / 2 && !used[tp.tmp - 1]){tm.tmp = tp.tmp - 1;q.push(tm);}if(tp.tmp % 2 == 0 && tp.tmp / 2 >= n / 2 && !used[tp.tmp / 2]){tm.tmp = tp.tmp / 2;q.push(tm);}}}int main(){int i;node tm;while(scanf("%d%d", &n, &k)!=EOF){if(n > k){printf("%d\n", n - k);continue;}//memset(used, false, sizeof(used));tm.step = 0;tm.tmp = k;q.push(tm);for(i = n / 2; i <= 2 * k; i ++){used[i] = false;}bfs();while(!q.empty())q.pop();}return 0;}