The Way to Home
A frog lives on the axis Ox and needs to reach home which is in the point n. She starts from the point 1. The frog can jump to the right at a distance not more than d. So, after she jumped from the point x she can reach the point x + a, where a is an integer from 1 to d.
For each point from 1 to n 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 1 and n.
Determine the minimal number of jumps that the frog needs to reach home which is in the point n from the point 1. Consider that initially the frog is in the point 1. If the frog can not reach home, print -1.
Input
The first line contains two integers n and d (2 ≤ n ≤ 100, 1 ≤ 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 s of length n, consisting of zeros and ones. If a character of the string s 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 s equal to one.
OutputIf 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 n from the point 1.
Examples8 4 10010101
2
4 2 1001
-1
8 4 11100101
3
12 3 101111100101
4
In the first example the from can reach home in two jumps: the first jump from the point 1 to the point 4 (the length of the jump is three), and the second jump from the point 4 to the point 8 (the length of the jump is four).
In the second example the frog can not reach home, because to make it she need to jump on a distance three, but the maximum length of her jump equals to two.
我的思路是从1起点开始,先加上最大跳跃步数,然后从这个下标往回找找到1,更新起点,答案加一,否则不能到达输出-1
code:
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
int main(){
char s[109];
int n,d;
scanf("%d%d",&n,&d);
getchar();
for(int i = 1; i <= n; i++){
scanf("%c",&s[i]);
}
int i = 1;
int ans = 0;
while(i <= n){//起点
int j = i + d;//每次从起点跳最远到达的下标
if(j > n){//如果从起点跳的最远下标超过了n肯定可达并结束
ans++;
break;
}
int flag = 0;
while(j > i){
if(s[j] == '1'){//找到第一个1停止
ans++;
flag = 1;
i = j;
break;
}
j--;
}
if(i == n) break;//如果恰好到了n退出循环
if(!flag){//如果没有1说明不能到达
printf("-1\n");
return 0;
}
}
printf("%d\n",ans);
return 0;
}