Leap Frog
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 676 Accepted Submission(s): 244
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 x
1,x
2,…, x
n where Jack or Jill may stand. Jill initially starts at position x
1, Jack initially starts at position x
2, and their goal is to reach position x
n.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 x
1,x
2,…, x
n where 0 <=x
1,x
2,…, x
n<= 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
题目的意思是初始第一个点和第二个点有两个人,人每次最多前进10步,两人轮番前进,每次是后面的人跳到前面的人的前面,,问任意一人走到最后他一个点最少多少步?
本来我们如果开dp[i][j]保存两个人的位置,题目很简单了,但是n有100000,数组开不下,我们发现每次最多走十步,那就是说只要取i之前10步以内的数就好
于是定义dp[10][100000],dp[i][j]为一个人在j位置骂另一个人在他左边i个点。
代码如下
#include<cstdio>
#include<cstring>
#include<cmath>
#include<iostream>
#include<algorithm>
using namespace std;
#define inf 0x3f3f3f3f
int dp[15][100005];
int a[100005];
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)
break;
if(a[i]-a[i-j]<=10)
{
for(int k=j+1; k<=10; k++)
{
if(i-k<1)
break;
if(a[i]-a[i-k]<=10)
{
if(dp[j][i]==-1&&dp[k-j][i-j]!=-1)
dp[j][i]=dp[k-j][i-j]+1;
else if(dp[k-j][i-j]!=-1)
dp[j][i]=min(dp[j][i],dp[k-j][i-j]+1);
}
}
}
}
}
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;
}