Codeforces Round #515 (Div. 3) B. Heaters (贪心)

-
题意:有\(n\)个桩子,\(1\)表示该位置有一个火炉,可以使两边距离为\(r\)的范围照亮,问最少使用多少炉子使得所有范围都被照亮.
-
题解:贪心,首先我们从\(r\)位置开始向左找,如果找到了就记录这个位置,然后答案+1,然后再从\(2*r-1\)这个位置开始向左找第一个没有标记的火炉,如果没有找到就直接输出\(-1\)结束,否则重复寻找的过程.
-
代码:
int n,r; int a[N]; bool st[N]; int main() { ios::sync_with_stdio(false);cin.tie(0); cin>>n>>r; for(int i=1;i<=n;++i){ cin>>a[i]; } int pos=r; int cnt=0; while(true){ if(a[pos]){ cnt++; st[pos]=true; if(pos+r-1>=n) break; else{ pos=pos+2*r-1; continue; } } while(a[pos]==0 && pos>=1 && !st[pos]) pos--; if(st[pos] || pos==0){ cout<<-1<<endl; return 0; } else{ cnt++; st[pos]=true; if(pos+r-1>=n) break; pos=pos+2*r-1; } } cout<<cnt<<endl; return 0; }
𝓐𝓬𝓱𝓲𝓮𝓿𝓮𝓶𝓮𝓷𝓽 𝓹𝓻𝓸𝓿𝓲𝓭𝓮𝓼 𝓽𝓱𝓮 𝓸𝓷𝓵𝔂 𝓻𝓮𝓪𝓵
𝓹𝓵𝓮𝓪𝓼𝓾𝓻𝓮 𝓲𝓷 𝓵𝓲𝓯𝓮

浙公网安备 33010602011771号