poj 2437

本文介绍了一种使用贪心算法解决泥水沟覆盖问题的方法,通过优化板子的放置策略来实现所有沟的有效覆盖。该算法通过排序和贪心选择,确保了在有限资源的情况下达到最优解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题意:有n个泥水沟,要你用L的板子把所有沟覆盖。

分析:贪心。每次把当前的沟覆盖,若之前的木板已把当前的沟覆盖则忽略,否则覆盖部分或完全没覆盖,需要考虑的是剩下沟的长度如何覆盖完全。

#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
struct node{
    int st,ed;
    bool operator<(const node &p)const{
        return st<p.st;
    }
};
const int MAX=10005;
node p[MAX];
int main(){
    int n,L,i,lastpos,ans,len,tmp;
    scanf("%d%d",&n,&L);
    for(i=0;i<n;i++)
        scanf("%d%d",&p[i].st,&p[i].ed);
    sort(p,p+n);
    for(lastpos=-1,ans=0,i=0;i<n;i++){//起始时上一块木板的末坐标很小。
        if(lastpos>=p[i].ed)
            continue;
        if(lastpos>p[i].st){
            len=p[i].ed-lastpos;
            tmp=(len+L-1)/L;//向上取整,不够L的部分要加一,即把当前的完全覆盖。
            lastpos=lastpos+tmp*L;
            ans+=tmp;
        }
        else{
            len=p[i].ed-p[i].st;
            tmp=(len+L-1)/L;
            lastpos=p[i].st+tmp*L;
            ans+=tmp;
        }
    }
    printf("%d\n",ans);
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值