广度优先队列(BFS)----
链接:http://acm.hrbust.edu.cn/index.php?m=ProblemSet&a=showProblem&problem_id=1012
Farmer John has been informed of the location of a fugitive cow and wants to catch her immediately. He starts at a point N (0 ≤ N ≤ 100,000) on a number line and the cow is at a point K (0 ≤ K≤ 100,000) on the same number line. Farmer John has two modes of transportation: walking and teleporting.
* Walking: FJ can move from any point X to the points X - 1 or X + 1 in a single minute
* Teleporting: FJ can move from any point X to the point 2 × X in a single minute.
If the cow, unaware of its pursuit, does not move at all, how long does it take for Farmer John to retrieve it?
Sample Input :5 17
100 100
Sample Output:
4
0
这个第一个代码我写的很具体,把广搜的每一个步骤,每一个过程,队列的五种操作都列的很清楚,下面这个广搜过程(BFS)函数可用来当做模板用 --- 如果觉得不错的话,第二个代码也提交了一次,写的比较抽象,不那么容易看懂,但是比较简洁;不过,对于不同的你来说,理解了这种方法,这种过程最重要; 最基本的广搜问题;
The Code Follows:
#include <cstdio> #include <cstdlib> #include <cstring> #include <iostream> using namespace std; const int MAX = 100001; const int LEFT = 0; const int RIGHT = 100000; bool flag[MAX]; typedef struct queue_ { int q[MAX]; int steps[MAX]; int head, tail; void init() //初始化队列; { head = tail = 0; memset(steps, 0, sizeof(steps)); } void in(int element) //入列; { q[tail++] = element; } int out() //出列; { return q[head++]; } bool empty() //清空队列; { return (tail - head == 0); } }queue; queue Q; inline bool inMap(int position) { return (LEFT <= position && position <= RIGHT); } inline void func(queue& Q, bool flag[], int position, int stp) { Q.in(position); Q.steps[position] = stp; flag[position] = true; } int BFS(queue& Q, int start, int target) { Q.init(); Q.in(start); memset(flag, false, sizeof(flag)); flag[start] = true; while (!Q.empty()) { int tmp = Q.out(); int stp = Q.steps[tmp]; if (tmp == target) { return stp; }else { if (inMap(tmp+1) && !flag[tmp+1]) { func(Q, flag, tmp+1, stp+1); } if (inMap(tmp-1) && !flag[tmp-1]) { func(Q, flag, tmp-1, stp+1); } if (inMap(tmp*2) && !flag[tmp*2]) { func(Q, flag, tmp*2, stp+1); } } } } int main() { int n, k; while (scanf("%d%d", &n, &k) != EOF) { printf("%d\n", BFS(Q, n, k)); } return 0; }
Methods II :
#include <iostream> #include <cstdio> #include <cstring> #define MAXN 1000005 using namespace std; typedef struct Node_ { int step, x; }Node; Node q[MAXN]; int s[3], v[MAXN]; int main() { int n, k; while(~scanf("%d%d", &n, &k)) { memset(v, 0, sizeof(v)); memset(s, 0, sizeof(s)); int rear = 0, front = 0, ii; int x1, x2, x3, flag = 0, ans = 0; q[rear].x = n; q[rear++].step = 0; v[n] = 1; while(front < rear) { ii = q[front].x; if(ii == k) { flag = 1; ans = q[front].step; break; } s[0]= ii + 1; s[1] = ii - 1; s[2] = ii*2; for(int i=0; i<3; i++) { if(s[i]>=0 && s[i]<=MAXN && !v[s[i]]) { q[rear].x = s[i]; q[rear++].step = q[front].step + 1; v[s[i]] = 1; } } front++; } if(flag) { printf("%d\n", ans); } } }后续解法待续。。。