题目链接:http://acm.hrbust.edu.cn/index.php?m=ProblemSet&a=showProblem&problem_id=1186点击打开链接
青蛙过河 | ||||||
| ||||||
Description | ||||||
在河上有一座独木桥,一只青蛙想沿着独木桥从河的一侧跳到另一侧。在桥上有一些石子,青蛙很讨厌踩在这些石子上。由于桥的长度和青蛙一次跳过的距离都是正整数,我们可以把独木桥上青蛙可能到达的点看成数轴上的一串整点:0,1,……,L(其中L是桥的长度)。坐标为0的点表示桥的起点,坐标为L的点表示桥的终点。青蛙从桥的起点开始,不停的向终点方向跳跃。一次跳跃的距离是s到t之间的任意正整数(包括s,t)。当青蛙跳到或跳过坐标为L的点时,就算青蛙已经跳出了独木桥。 题目给出独木桥的长度L,青蛙跳跃的距离范围s,t,桥上石子的位置。你的任务是确定青蛙要想过河,最少需要踩到的石子数。 | ||||||
Input | ||||||
有多组测试数据。 对于每组测试数据,第一行四个正整数L, s, t, n(1 <= L <= 10^5, 1 <= s <= t <= 10,1 <= n <= 100),分别表示独木桥的长度,青蛙一次跳跃的最小距离,最大距离,及桥上石子的个数。第二行有n个不同的正整数分别表示这n个石子在数轴上的位置(数据保证桥的起点和终点处没有石子)。所有相邻的整数之间用一个空格隔开。 | ||||||
Output | ||||||
每组测试数据仅输出一行,包括一个整数,表示青蛙过河最少需要踩到的石子数。 | ||||||
Sample Input | ||||||
10 2 3 5 2 3 5 6 7 | ||||||
Sample Output | ||||||
2 |
dp问题 一开始想着贪心 去最大空位或者全为石子时取最大距离 然后wa了 后面想到组数据:
10 2 3 6
2 3 5 6 8 9
从头扫一遍 记录当前位置可到达的位置 取最小值
注意永远不能到达的位置需要跳过
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include<algorithm>
#include <math.h>
#include <string.h>
#include <limits.h>
#include <string>
#include <queue>
#include <stack>
using namespace std;
int a[200000];
int book[200000];
int step[2000000];
int main()
{
int l;int s;int t;int n;
while(scanf("%d%d%d%d",&l,&s,&t,&n)!=EOF)
{
memset(a,0,sizeof(a));
memset(book,0,sizeof(book));
for(int i=0;i<=200000;i++)
{
step[i]=INT_MAX;
}
for(int i=0;i<n;i++)
{
int nn;
scanf("%d",&nn);
a[nn]=1;
}
book[0]=1;
step[0]=0;
for(int i=0;i<=l+t;i++)
{
if(book[i]==1)
{
for(int j=s;j<=t;j++)
{
book[i+j]=1;
if(a[i+j])
step[i+j]=min(step[i+j],step[i]+1);
else
{
step[i+j]=min(step[i+j],step[i]);
}
}
}
}
int num=step[l];
for(int i=l;i<=l+t;i++)
num=min(num,step[i]);
printf("%d\n",num);
}
}