poj Muddy roads(贪心or递推)

来源:互联网 发布:罗辑思维 人工智能 编辑:程序博客网 时间:2024/05/22 06:38

    这道题也是今下午练习赛的题目,说到方法,说是用贪心比较多,而我用的是递推啊...难道因为这个时间才那么长吗??

    这道题题目的描述太坑了,一开始以为每一段dirt road的长度是 起点减去终点的值+2(包含两个端点),要用板子覆盖这段长度,结果怎么也对不上样例微笑(HINT也很难懂啊),后俩发现我理解错了,以为dirt road的长度从起点到终点包含多少个点微笑,其实dirt road的长度就是起点到终点包含的各个点之间的距离之和。

   正确的题意为:有n滩泥 木板长度为l 求最少需要多少木板才能覆盖这些泥

   思路:把泥升序排序,分三种情况讨论

1、前一个木板完全覆盖了当前的泥 跳过

2、前一个木板覆盖了一部分 则计算铺完剩下的泥需要多少木板

3、前一个木板完全没接触到当前的木板 则更新端点 

Muddy roads
Time Limit: 1000MS Memory Limit: 65536KTotal Submissions: 3287 Accepted: 1510

Description

Farmer John has a problem: the dirt road from his farm to town has suffered in the recent rainstorms and now contains (1 <= N <= 10,000) mud pools. 

Farmer John has a collection of wooden planks of length L that he can use to bridge these mud pools. He can overlap planks and the ends do not need to be anchored on the ground. However, he must cover each pool completely. 

Given the mud pools, help FJ figure out the minimum number of planks he needs in order to completely cover all the mud pools.

Input

* Line 1: Two space-separated integers: N and L 

* Lines 2..N+1: Line i+1 contains two space-separated integers: s_i and e_i (0 <= s_i < e_i <= 1,000,000,000) that specify the start and end points of a mud pool along the road. The mud pools will not overlap. These numbers specify points, so a mud pool from 35 to 39 can be covered by a single board of length 4. Mud pools at (3,6) and (6,9) are not considered to overlap. 

Output

* Line 1: The miminum number of planks FJ needs to use.

Sample Input

3 31 613 178 12

Sample Output

5

Hint

INPUT DETAILS: 

FJ needs to use planks of length 3 to cover 3 mud pools. The mud pools cover regions 1 to 6, 8 to 12, and 13 to 17. 

OUTPUT DETAILS: 

FJ can cover the mud pools with five planks of length 3 in the following way: 
                   111222..333444555....                   .MMMMM..MMMM.MMMM....                   012345678901234567890

 

     AC代码:

#include<cstdio>
#include<algorithm>
using namespace std;
typedef struct
{
    int s,e;
}node;
node a[10010];
bool cmp(node a,node b)
{
    return a.s<b.s;
}
int main()
{
    int n,l;
    scanf("%d%d",&n,&l);
    for(int i=1;i<=n;i++) scanf("%d%d",&a[i].s,&a[i].e);
    int ans=0;
    int last=-1;//last表示铺完板子后的下一个端点(该端点还未铺板子,该点具体需不需要铺板子,需要进一步判断)
    sort(a+1,a+1+n,cmp);
    for(int i=1;i<=n;i++)
    {
        if(last>=a[i].e) continue;
        else if(last>a[i].s)
        {
            int len=a[i].e-last;
            int num=(len+l-1)/l;//通过递推关系可得dirty road的长度,板子长度和板子数量的关系,这个式子非常重要!!
            last+=num*l;
            ans+=num;
        }
        else
        {
            int len=a[i].e-a[i].s;
            int num=(len+l-1)/l;
            last=a[i].s+num*l;
            ans+=num;
        }
    }
    printf("%d\n",ans);
    return 0;
}

原创粉丝点击