题目描述
A frog lives on the axis OxOx and needs to reach home which is in the point nn . She starts from the point 11 . The frog can jump to the right at a distance not more than dd . So, after she jumped from the point xx she can reach the point x+ax+a , where aa is an integer from 11 to dd .
For each point from 11 to nn is known if there is a lily flower in it. The frog can jump only in points with a lilies. Guaranteed that there are lilies in the points 11 and nn .
Determine the minimal number of jumps that the frog needs to reach home which is in the point nn from the point 11 . Consider that initially the frog is in the point 11 . If the frog can not reach home, print -1.
输入格式
The first line contains two integers nn and dd ( 2<=n<=1002<=n<=100 , 1<=d<=n-11<=d<=n−1 ) — the point, which the frog wants to reach, and the maximal length of the frog jump.
The second line contains a string ss of length nn , consisting of zeros and ones. If a character of the string ss equals to zero, then in the corresponding point there is no lily flower. In the other case, in the corresponding point there is a lily flower. Guaranteed that the first and the last characters of the string ss equal to one.
输出格式
If the frog can not reach the home, print -1.
In the other case, print the minimal number of jumps that the frog needs to reach the home which is in the point nn from the point 11 .
题意翻译
题目描述
一只青蛙现在在一个数轴上,它现在要从点 11 跳到点 nn ,它每次可以向右跳不超过 dd 个单位。比如,它可以从点 xx 跳到点 x+ax+a ( 1<=a<=d )(1<=a<=d) 。特别的,青蛙只能在有百合花的点上停留。保证点 11 和点 nn 之间有一些点有百合花。请输出青蛙到达点 nn 的最小跳跃次数。
输入输出格式
输入格式
输入的第一行包括两个正整数 nn 和 dd ( 2<=n<=100, 1<=d<=n-1 )(2<=n<=100,1<=d<=n−1) 。 输入的第二行是一个长度为 nn 的无空格字符串,由0
和1
组成,表示哪些点上有百合花(1
表示有)。保证点 11 和点 nn 有百合花。
输出格式
输出青蛙的最小跳跃次数。如果它不可能到达,输出-1。
输入输出样例
说明
在样例1中,青蛙可以从点 11 跳3个单位到点 44 ,再从点 44 跳4个单位到点 88 . 在样例2中,青蛙不能到达点 nn ,因为它至少需要跳3个单位,但它最多只能跳2个单位。
由 @星烁晶熠辉 提供翻译
源码:
#include <iostream>
#include <stdio.h>
#include <string>
#include <iomanip>
#include <algorithm>
#include <stdlib.h>
#define inf 0x3f3f3f3f
using namespace std;
int main()
{
int n, d;
cin >> n >> d;
string way;
cin >> way;
int time = 0;
int start = 0; //当前下标位置
int end = 0;
bool flag = false;
while (start <= 300) //循环,这个条件其实无所谓,只要大于字符串与d的长度之和
{
if (way[start] == '1') { //如果当前字符为“1”,则表示可以落点。这里从0下标开始
//根据题意,0下标一定为“1”
start = start + d; //从当前位置向后移动最大长度d,先不管是不是“1”
time++; //跳跃次数
end = 0;
}
else
{
start--; //如果此时不是“1”,就倒退一位,下标向左移动一位
end++; //记录移动了几次,如果移动次数等于d,相当于又回到了一开始的数,没办法继续往下跳,只会无限循环
}
if (end == d) {
break; //打破循环,此种情况无解
}
if (start >= way.length() - 1) { //如果最后一跳超过了字符串总长度,那么一定能跳到终点。字符串长度减一是为了对应下标
flag = true; //此种情况有解,跳出循环
break;
}
}
if (flag == true) {
cout << time;
}
else
{
cout << -1;
}
}
这里因为我忘了每次找到新的跳跃点时,需要把end重置为0.
然后浪费了整整4个小时来找问题,真是寄了。这道题就是用贪心算法,每次青蛙都跳最大值d,看能不能跳,不能跳就跳d-1,再判断能不能跳,还不能跳就d-1-1,再判断,依次类推。如果发现d减到0了还不能跳,这题就无解了,输出-1.如果发现已经跳的距离大于总距离了,就输出结果 。