首页 > 代码库 > hdu 3455 Leap Frog
hdu 3455 Leap Frog
Leap Frog
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 623 Accepted Submission(s): 219
Problem Description
Jack and Jill play a game called "Leap Frog" in which they alternate turns jumping over each other. Both Jack and Jill can jump a maximum horizontal distance of 10 units in any single jump. You are given a list of valid positions x1,x2,…, xn where Jack or Jill may stand. Jill initially starts at position x1, Jack initially starts at position x2, and their goal is to reach position xn.Determine the minimum number of jumps needed until either Jack or Jill reaches the goal. The two players are never allowed to stand at the same position at the same time, and for each jump, the player in the rear must hop over the player in the front.
Input
The input file will contain multiple test cases. Each test case will begin with a single line containing a single integer n (where 2 <= n <= 100000). The next line will contain a list of integers x1,x2,…, xn where 0 <=x1,x2,…, xn<= 1000000. The end-of-fi le is denoted by a single line containing "0".
Output
For each input test case, print the minimum total number of jumps needed for both players such that either Jack or Jill reaches the destination, or -1 if neither can reach the destination.
Sample Input
6 3 5 9 12 15 17 6 3 5 9 12 30 40
Sample Output
3 -1
Source
2009 Stanford Local ACM Programming Contest
题意:
给定一个从小到大的正整数序列表示位置,刚开始A在序列中第一个元素位置,B在序列中第二个元素位置,接下来A要跳到B的后面的位置,且跳跃的距离不能超过10,求其中一人到达最后一个位置时,两人跳跃的总次数最少;
题解:
首先想到的是普通的DP,dp[i][j]表示一个人在第i个位置,另一个人在第j个位置所需要的最少跳跃次数。但是n<=100000,这样内存会超,题目中说跳跃距离不超过10,也就是说第j个位置只有前面10个是有用的,于是dp[i][j]的i可以表示一个人在第j位置,另一个在第j-i个位置。
i为当前要到达的第i个位置,j是前一个人在第i-j个位置,k是后一个人在i-j-k个位置,现在从第i-j-k跳到i位置,所以dp[j][i]=min(dp[j][i],dp[k][i-j]+1),dp[k][i-j]是状态为一个在第i-j个位置,一个在i-j-k个位置时的最小跳跃次数。
代码:
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> using namespace std; const int maxn=100000+100; const int inf=199999999; int dp[12][maxn]; int a[maxn]; int main() { int n; while(~scanf("%d",&n)&&n) { for(int i=1;i<=n;i++) scanf("%d",&a[i]); memset(dp,-1,sizeof(dp)); dp[1][2]=0; for(int i=3;i<=n;i++) { for(int j=1;j<=10;j++) { if(i-j>=1&&a[i]-a[i-j]<=10) { for(int k=1;k<=10;k++) { if(i-j-k>=1&&a[i]-a[i-j-k]<=10) { if(dp[k][i-j]!=-1)//判断是否存在一个在第i-j个位置,一个在i-j-k个位置 { if(dp[j][i]==-1) { dp[j][i]=dp[k][i-j]+1; } else { dp[j][i]=min(dp[j][i],dp[k][i-j]+1); } } } } } else break; } } int ans=inf; for(int i=1;i<=10;i++) if(dp[i][n]!=-1) ans=min(ans,dp[i][n]); if(ans==inf) printf("-1\n"); else printf("%d\n",ans); } return 0; }
hdu 3455 Leap Frog
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。