Greedy.
Only consider the position of negative numbers, first fill the interval smaller, and then fill the larger interval. If the filling is not filled, if there is superfluous left to the last negative number to the end of the road.
#include <cstdio>#include<cstring>#include<string>#include<cmath>#include<vector>#include<queue>#include<algorithm>#include<Set>using namespacestd;intn,k,a[200010],sz;structx{intL,r,len;} s[200010];vector<int>v;intf[200010];BOOLCMP (x A, x B) {returna.len<B.len;}intMain () {scanf ("%d%d",&n,&k); for(intI=1; i<=n; i++) scanf ("%d",&A[i]); intsum=0; for(intI=1; i<=n; i++)if(a[i]<0) f[i]=1, sum++; if(sum>k) printf ("-1\n"); Else { if(sum==0) printf ("0\n"); Else { for(intI=1; i<=n; i++)if(a[i]<0) V.push_back (i); for(intI=0; I<v.size ()-1; i++) S[sz]. L=v[i], S[sz]. r=v[i+1], S[sz].len = S[sz]. R-S[SZ]. L-1, sz++; Sort (s,s+sz,cmp); Sum=k-sum; for(intI=0; i<sz; i++) { if(sum>=S[i].len) { for(intJ=s[i]. L;j<=s[i]. r;j++) f[j]=1; Sum=sum-S[i].len; } } if(sum>=n+1-v[v.size ()-1]-1) { for(intI=v[v.size ()-1];i<=n;i++) f[i]=1; } //for (int i=1;i<=n;i++) printf ("%d", F[i]); intans=0; intf1=1, f2=N; for(intI=1; i<=n;i++) { if(f[i]==0)Continue; Else{f1=i; Break;} } for(inti=n;i>=1; i--) { if(f[i]==0)Continue; Else{f2=i; Break;} } ans=ans+1; if(f2!=n) ans=ans+1; for(inti=f1+1; i<=f2;i++) { if(f[i]!=f[i-1]) ans++; } printf ("%d\n", ans); } } return 0;}
Codeforces 747D Winter is Coming