POJ3278 是一道经典的BFS题.
1. 原题:
Farmer John has been informed of the location of a fugitive cow and wants to catch her immediately. He starts at a pointN(0 ≤ N ≤ 100,000) on a number line and the cow is at a pointK(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 pointXto the points X - 1 orX+ 1 in a single minute
* Teleporting: FJ can move from any point X to the point 2 ×Xin 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?
Input
Line 1: Two space-separated integers:Nand K
Output
Line 1: The least amount of time, in minutes, it takes for Farmer John to catch the fugitive cow.
Sample Input
5 17
Sample Output
4
Hint
The fastest way for Farmer John to reach the fugitive cow is to move along the following path: 5-10-9-18-17, which takes 4 minutes.
.
2. 题意分析
题意为给定起点和终点, 求出从起点到终点的最少步数,其中每一步可以是往前一步、后退一步以及当前步数乘以2.
输入: N 和K
输出: 最少步数
如输入 5 17
输出 4
( 5 -10-9-18-17, 即 5 *2 = 10, 10-1=9, 9*2=18, 18-1=17, 步数为4)
3. 算法选取
模拟下这过程,当前在n点,下一个点即可能是 n-1 或 n+1 或n*2 ,只要不超出范围(0 - 100000)
很容易想到使用BFS(广度搜索优先).
(1)一般BFS 会使用队列,主要队列不为空,把队头出列,并把从该点出发到达符合条件的点加入队尾.
(2)使用队列需要考虑空间复杂度,即是否会内存溢出。
而题目中点最多为100000,并且每个点只要是先访问过,后面都不会入队列(因为先访问表示已是最少步数了,无需再处理)
因此也无需使用循环队列或者双队列.
(3) BFS 经常会有截枝操作以节省时间,本题中如果起始点 > 目的点,明显只能通过-1 操作以省步数,即起始点减去目的点的值为结果.
4.数据结构
location[MAX_SIZE+2] :
表示每个点, 其值表示最先访问的步数, 初始化为INF(可以看做无穷大,方便比较更新,也可初始化0)。
queue[MAX_SIZE+2]: 即队列
5. 完整代码
Memory: 860K Time: 0MS
#include <stdio.h>
#define MAX_SIZE 100000
#define INF 1000000
int location[MAX_SIZE + 2]; //
int startLoc, endLoc;
int minStep;
// queue
int queue[MAX_SIZE + 2];
int front;
int rear;
// 入队列,插入队尾
void myin(int x){
queue[rear] = x;
rear++;
}
// 队头出队列
int myout(){
int res;
res = queue[front];
front++;
return res;
}
// 判断队列是否为空
bool isEmpty(){
return (front == rear);
}
int main(){
int i, j;
int step;
int curr;
int next;
//freopen("input.txt", "r", stdin);
scanf("%d %d", &startLoc, &endLoc);
minStep = 0;
front = 0;
rear = 0;
step = 0;
for(i = 0; i <= MAX_SIZE; i++ ){
location[i] = INF; // init
}
if(startLoc >= endLoc){ // 起始点 > 目的点
minStep = startLoc - endLoc;
}else{
myin(startLoc); //入队列
location[startLoc] = 0;
curr = startLoc;
while(isEmpty() != true){
curr = myout(); // 出队列作为当前点
if(curr == endLoc){ // 已经达到目的点,退出循环结束
minStep = location[curr];
break;
}
for( i = 0; i < 3; i ++){
if(i ==0){ // 退后一步
next = curr - 1;
}else if(i == 1){ // 往前一步
next = curr + 1;
}else{ // 往前2倍
next = curr *2;
}
if(next < 0 || next > MAX_SIZE) // 越界
continue;
if(location[next] > location[curr] + 1){ // 入队列条件,即没访问过,也可与INF比较
location[next] = location[curr] + 1; // 记录步数
myin(next); // 入队列继续找
}
}
}
}
printf("%d", minStep);
return 0;
}