poj 3278( 搜尋 )
阿新 • • 發佈:2019-02-18
Catch That Cow
and K
Time Limit: 2000MS | Memory Limit: 65536K |
Total Submissions: 29250 | Accepted: 9000 |
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: NOutput
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
題目型別:搜尋 題目描述:略 題目分析:略 程式碼如下:#include <stdio.h> #include <string.h> #define N 100001 int visit[N]; struct Point{ int x; int step; } queue[N*2],c,r,sp; int bfs(int start,int target){ int top = 0,end = 0; if(start == target){ return 0; } memset(visit,0,sizeof(visit)); visit[start] = 1; sp.x = start; sp.step = 0; queue[top] = sp; while(top <= end){ c = queue[top]; if(c.x + 1 < N && visit[c.x+1] == 0){ visit[c.x+1] = 1; r.x = c.x+1; r.step = c.step+1; if(r.x == target){ return r.step; } queue[++end] = r; } if(c.x - 1 >=0 && visit[c.x-1] == 0) { visit[c.x-1] = 1; r.x = c.x-1; r.step = c.step+1; if(r.x == target){ return r.step; } queue[++end] = r; } if(c.x * 2 < N && visit[c.x*2] == 0){ visit[c.x*2] = 1; r.x = c.x*2; r.step = c.step +1; if(r.x == target){ return r.step; } queue[++end] = r; } top++; } return -1; } int main() { int s,t; while(scanf("%d%d",&s,&t) != EOF){ printf("%d\n",bfs(s,t)); } return 0; }