POJ 3278 BFS题
2016-01-23 23:18
232 查看
大致题意:
有n,k,在x轴上,然后农夫用三种 head-1, head+1 或 head*2 去走,问最少多少步可以将牛拉回来;
PS:queue队列,要记好加入队列,出队,已经保存出队前一个元素;
要牢记需要剪枝;如果超出范围必须跳过,不然会RE;
代码如下:
明天再复习一个
有n,k,在x轴上,然后农夫用三种 head-1, head+1 或 head*2 去走,问最少多少步可以将牛拉回来;
PS:queue队列,要记好加入队列,出队,已经保存出队前一个元素;
要牢记需要剪枝;如果超出范围必须跳过,不然会RE;
代码如下:
#include <iostream> #include <string.h> #include <queue> using namespace std ; const int MAX = 100010; int n , k; int step[MAX],vis[MAX]; queue<int>Q; int sum; int bfs(int n, int k) { int head, next; Q.push(n); vis = true; step = 0; while (!Q.empty()) { head = Q.front(); Q.pop(); for (int i = 0; i < 3; i++) { if (i == 0) next = head - 1; else if (i == 1) next = head + 1; else next = head * 2; if (next > MAX || next < 0 || vis[next]) continue; if (vis[next]==false) { Q.push(next); step[next] = step[head] + 1; vis[next] = true; } if (next == k) return step[next]; } } } int main() { cin>>n>>k; sum=bfs(n,k); if(n>=k) { cout<<n-k<<endl; } else cout<<sum<<endl; return 0 ; }
明天再复习一个