描述
Big Street is an array consisting of n elements. There are street lamps in some positions of the array. If there is a lamp in the position i, the i-th element of the array is 1, otherwise the i-th element of the array is 0.
Each lamp has a power m (m is the same for all lamps). This power means that the lamp at the position pos can light up all the elements in range [pos-m+1,pos+m-1].
Your task is to find the minimum lamps needed to light up the whole street (all the elements of the array) or say that it is impossible to light up the whole street.
输入
The first line of the input contains two integers n and m (1≤n,m≤1000)— the number of elements in the array and the power of lamps.
The second line contains n integers a_1,a_2,…,a_n (0≤a_i≤1)—Big Street description.
输出
Print one integer — the minimum number of lamps needed to light up the whole street or -1 if it is impossible to do it.
输入样例 1
6 2
0 1 1 0 0 1
输出样例 1
3
输入样例 2
4 5
0 0 0 0
输出样例 2
-1
输入样例 3
10 3
0 0 1 1 0 1 0 0 0 1
输出样例 3
3
提示
In the last example, the lamp at the position 3 lights up elements [1,5], the light at the position 6 lights up elements [4,8] and the lamp at the position 10 lights up elements [8,10]. So, the answer is 3.
来源
NEEPU 13th ACM
代码
#include <iostream>
using namespace std;
struct L{
long long status;
long long lPos;
long long rPos;
long long num;
};
int main(){
int n, m, cnt, min = 1010;
int pos, i, j;
struct L lamp[1010];
cin >> n >> m;
for(pos = 1; pos <= n; pos++){
cin >> lamp[pos].num;
if(lamp[pos].num == 1){
lamp[pos].lPos = pos - m + 1;
lamp[pos].rPos = pos + m - 1;
if(pos - m + 1 < 1) lamp[pos].lPos = 1;
if(pos + m - 1 > n) lamp[pos].rPos = n;
for(i = lamp[pos].lPos; i <= lamp[pos].rPos; i++){
lamp[i].status = 1;
}
}
}
for(i = 1; i <= n; i++){
if(lamp[i].rPos == n && lamp[i].num == 1){
for(j = i + 1; j <= n; j++){
lamp[j].num = 0;
}
}
}
for(i = n; i >= 1; i--){
if(lamp[i].lPos == 1 && lamp[i].num == 1){
for(j = i - 1; j >= 1; j--){
lamp[j].num = 0;
}
}
}
for(i = 1; i <= n; i++){
if(lamp[i].num == 1){
cnt = 0;
if(lamp[i].lPos == 1 && lamp[i].rPos == n){
cout << "1";
return 0;
}
for(j = n; j > i; j--){
if(lamp[j].num == 1){
if(lamp[i].rPos + 1 >= lamp[j].lPos){
for(pos = i + 1; pos <= j - 1; pos++){
if(lamp[pos].num == 1){
lamp[pos].num = 0;
}
}
}
}
}
for(j = 1; j <= n; j++){
if(lamp[j].num == 1) cnt++;
}
if(cnt < min) min = cnt;
}
}
for(i = 1; i <= n; i++){
if(lamp[i].status == 0){
cout << "-1";
return 0;
}
}
cout << min;
return 0;
}