感觉对这个算法理解不是很透彻,就是个贪心嘛,代码调了半天调不出来
贪心:左端点合法的约束下,一直选能更新到最大右区间的线段
#include <bits/stdc++.h>
using namespace std;
#define ll long long
const ll MOD = 1e9+7;
#define pb push_back
#define mp(a,b) make_pair(a,b)
int n,m;
vector<pair<int,int> > G;
int main(){
ios::sync_with_stdio(0);int n,r;cin>>n>>r;for(int i=1;i<=n;++i){
int data;cin>>data;int L=max(1,i-r+1);int R=min(n,i+r-1);if(data) G.pb(mp(L,R));}sort(G.begin(),G.end());int now=1;int ans=0;int temp=0;int index=0;int len=G.size();bool ok=true;while(now<=n){
temp=0;while(index<len&&G[index].first<=now){
temp=max(temp,G[index].second);++index;}if(!temp){
ok=0;break;}now=temp+1;ans++;}if(!ok){
printf("-1\n");}else printf("%d\n",ans);return 0;
}