xlh刷书日记(BFS)

POJ 3278
Description

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?

Input
Line 1: Two space-separated integers: N and 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.

Source
USACO 2007 Open Silver

看到这个题开始想用动态规划,可是想了想还是用bfs比较好,对于一个点有三种转移方法,first+1,first-1和first*2。考虑到时间复杂度的问题,我们要对其进行剪枝,具体方法是判重。还有就是求最小次数,我们可以用批次来记录,记录哪些点是同一批,没找到就是0,发现就是非零。下一批次与上一批次之间相差一。用数组存放,多的不说,直接上代码

#include<iostream>
#include<stdio.h>
#include<algorithm>
#include<queue>
#include<string.h>
using namespace std;
#define check(k) (k>=0&&k<=100000)
queue<int>q;
int hadfind[200010];
int flag=0,k;
void bfs(int start){
	q.push(start);
	hadfind[start]=1;//记录批次 ,司机批次 
	int first,next;
	while(!q.empty()){
		if(hadfind[k]!=0){
			break;
		}
		 first=q.front();//
		 q.pop();
		 for(int i=0;i<3;i++){
		 	if(i==0) next=first-1;
		 	else if(i==1) next=first+1;
		 	else next=first*2;
		 	if(check(next)&&hadfind[next]==0){
		 		hadfind[next]=hadfind[first]+1;
		 		q.push(next);
			 }
		 }//同层标记同层 
	} 
}
int main(){
	int n;
	memset(hadfind,0,sizeof(hadfind));
	cin>>n>>k;
	bfs(n);
	cout<<hadfind[k]-1<<endl;
	return 0;
}

其实数组还可以开小一点,但寻思着已经ac了就没必要做改动了

上一篇:A - Monthly Expense


下一篇:OAuth 2.0 扩展协议之 PKCE