题意描述
Vova’s house is an array consisting of n elements (yeah, this is the first problem, I think, where someone lives in the array). There are heaters in some positions of the array. The i-th element of the array is 1 if there is a heater in the position i, otherwise the i-th element of the array is 0.
Each heater has a value r (r is the same for all heaters). This value means that the heater at the position pos can warm up all the elements in range [pos−r 1;pos r−1].
Vova likes to walk through his house while he thinks, and he hates cold positions of his house. Vova wants to switch some of his heaters on in such a way that each element of his house will be warmed up by at least one heater.
Vova’s target is to warm up the whole house (all the elements of the array), i.e. if n=6, r=2 and heaters are at positions 2 and 5, then Vova can warm up the whole house if he switches all the heaters in the house on (then the first 3 elements will be warmed up by the first heater and the last 3 elements will be warmed up by the second heater).
Initially, all the heaters are off.
But from the other hand, Vova didn’t like to pay much for the electricity. So he wants to switch the minimum number of heaters on in such a way that each element of his house is warmed up by at least one heater.
Your task is to find this number of heaters or say that it is impossible to warm up the whole house.
给定n个序列,序列值为1表示该地方有一个加热器,每个加热器加热的半径为r,询问最少开启多少个加速器可以使所有地方加热,如果不能输出-1
思路
我们从贪心的角度来考虑,要想让加热器数量最小,那么要尽量选择开启距离该位置较远并且能够加热到该点的加热器,需要注意的是,如果该点已经存在加热器,不能跳过该点,而需要开启加热器,次数也应该加1.
AC代码
代码语言:javascript复制#include<bits/stdc .h>
#define x first
#define y second
#define IOS ios::sync_with_stdio(false);cin.tie(0);
using namespace std;
typedef unsigned long long ULL;
typedef pair<int,int> PII;
typedef pair<long,long> PLL;
typedef pair<char,char> PCC;
typedef long long LL;
const int N=1010;
const int M=150;
const int INF=0x3f3f3f3f;
const int MOD=998244353;
int used[N];
void solve(){
int n,r;cin>>n>>r;
for(int i=1;i<=n;i ) cin>>used[i];
int pos=1;
int ans=0;
while(pos<=n){
int idx=0;
int st=min(pos r-1,n);
int ed=max(pos-r 1,1);
for(int i=st;i>=ed;i--){
if(used[i]){
idx=i;
break;
}
}
if(!idx){
cout<<-1<<endl;
return;
}
pos=idx r;
ans ;
}
cout<<ans<<endl;
}
int main(){
IOS;
solve();
return 0;
}