题意:
0和1组成的长度为n的序列,若pos位置为1,那么这个1可以影响[pos - r + 1 , pos + r - 1]这个区间,问最少多少个1可以影响[1,n],如果不存在输出-1。
题解:
1.贪心。维护一个last,表示当前被影响的最右端,然后从右向左找可以与last+1有交集的1,若找不到直接输出-1。
2.注意以n为起点从右向左找1,并不是可以找到最左端的,而是找到可以影响last+1的位置。
#include<bits/stdc++.h>
using namespace std;
#define N 1005
int main()
{
int n , r , a[N] ;
int i , j ;
int last , pos , num ;
scanf("%d%d" , &n , &r) ;
for(i = 1 ; i <= n ; i ++)
scanf("%d" , &a[i]) ;
last = 0 ;
num = 0 ;
while(last < n)
{
pos = -1 ;
for(i = n ; i >= max(1 , last - r + 2) ; i --)
if(a[i] == 1 && i - r + 1 <= last + 1)
{
pos = i ;
break ;
}
if(pos == -1)
{
printf("-1") ;
return 0 ;
}
num ++ ;
last = pos + r - 1 ;
}
printf("%d" , num) ;
}