POJ 3278 Catch That Cow
题目链接:http://poj.org/problem?id=3278
题目大意:约翰在点N,牛在K,约翰抓牛,约翰一秒走到N+1,N-1或N*2,问多长时间抓到牛。
解题思路:因为让我加深了对DP的看法所以写的。由于可以向前,向后以及翻跟头走二倍,因此会出现跳到后面再回到前面的情况,那么这就不符合DP的条件了。但是实际上跳到后面也是从前面跳过去的,因此相当于是从前面多走了一次然后走到这一步。
代码:
1 const int maxn = 1e5 + 5;
2 int n, k;
3 int dp[maxn];
4
5 int solve(){
6 memset(dp, 0x3f, sizeof(dp));
7 for(int i = 0; i <= k; i++) dp[i] = abs(n - i);
8 for(int i = n; i <= 100000; i++){
9 if(i & 1){
10 if(dp[i - 1] + 1< dp[i]) dp[i] = dp[i - 1] + 1;
11 if(dp[(i + 1) / 2] + 2< dp[i]) dp[i] = dp[(i + 1) / 2] + 2;
12 if(dp[i / 2] + 2 < dp[i]) dp[i] = dp[i / 2] + 2;
13 }
14 else{
15 if(i > 0 && dp[i - 1] + 1 < dp[i]) dp[i] = dp[i - 1] + 1;
16 if(dp[(i + 2) / 2] + 3 < dp[i]) dp[i] = dp[(i + 2) / 2] + 3;
17 if(dp[i / 2] + 1 < dp[i]) dp[i] = dp[i / 2] + 1;
18 }
19 }
20 return dp[k];
21 }
22
23 int main(){
24 scanf("%d %d", &n, &k);
25 if(n >= k)
26 printf("%d\n", n - k);
27 else{
28 int ans = solve();
29 cout << ans << endl;
30 }
31 return 0;
32 }
题目:
Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 96558 | Accepted: 30300 |
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
Output
Sample Input
5 17
Sample Output
4
Hint
Source