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 200001
bool 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;
}