跳到正文

题解

题解:P12947 [GCJ Farewell Round #1] Illumination Optimization

4041nofoundGeoge约 3 分钟
原文
文章信息与版本

文章信息

发布
2025年6月27日
收录
2025年12月12日
更新
2026年11月20日
篇幅
约 3 分钟
题目
P12947

版本

  1. v1当前

水题。出题人你是不是有病,还要输出第几行。

题目大意

O 让你在 0∼M0\sim M 的数轴上选择任意个指定位置安装灯泡,灯泡光照半径为 RR,问最少指定多少个位置可以使数轴全覆盖。

思路

考虑贪心。

最开始照亮的地方是 00,然后我们查找每个位置的左边界刚好(或差不多)能覆盖这个结点,我们就选这个结点,然后能照亮的地方就是这个结点的右边界,即(当前点位 +R+R),我们继续查找左边界能刚好(或差不多)覆盖这个结点 ⋯\cdots 直到覆盖到右边界 MM,我们选的结点数 resres 就是答案,可以证明这是最优解。

证明:

设全长为 LL,贪心选择的第一个结点 rr 光照范围为 [0,r+R][0,r+R],剩下的 (r+R,L](r+R,L] 应一定与 [0,r+R][0,r+R] 一样存在最优解,因此贪心一定为最优解。

代码

C++
#include<bits/stdc++.h>
using namespace std;
int x[100005];
int main(){
    int t;
    cin>>t;
    int q=t;
    while(t--){//我偏不用for循环
        int m,r,n;
        cin>>m>>r>>n;
        for(int i=1;i<=n;i++){
            cin>>x[i];
        }
        int i=1;
        int pos=0;
        int maxn=-1;
        int res=0;
        bool poss=true;
        while(pos<m){
            maxn=-1;
            while(i<=n&&x[i]-r<=pos){
                maxn=x[i],i++;
            }
            if(maxn==-1){
                poss=false;
                break;
            }
            res++;
            pos=maxn+r;
            if(pos>=m)break;
            if(i>n||x[i]-r>pos){
                poss=false;
                break;
            }
        }
        cout<<"Case #"<<q-t<<": ";
        if(poss)cout<<res;
        else cout<<"IMPOSSIBLE";
        cout<<"\n";
    }

    return 0;
}
原文
存档评论1 条抓取于