1. 程式人生 > >POJ 3616 Milking Time

POJ 3616 Milking Time

題目描述:

Bessie is such a hard-working cow. In fact, she is so focused on maximizing her productivity that she decides to schedule her next N (1 ≤ N ≤ 1,000,000) hours (conveniently labeled 0..N-1) so that she produces as much milk as possible.

Farmer John has a list of M (1 ≤ M ≤ 1,000) possibly overlapping intervals in which he is available for milking. Each interval i

has a starting hour (0 ≤ starting_houriN), an ending hour (starting_houri < ending_houriN), and a corresponding efficiency (1 ≤ efficiencyi ≤ 1,000,000) which indicates how many gallons of milk that he can get out of Bessie in that interval. Farmer John starts and stops milking at the beginning of the starting hour and ending hour, respectively. When being milked, Bessie must be milked through an entire interval.

Even Bessie has her limitations, though. After being milked during any interval, she must rest R (1 ≤ RN) hours before she can start milking again. Given Farmer Johns list of intervals, determine the maximum amount of milk that Bessie can produce in the N hours.

Input

* Line 1: Three space-separated integers: N

, M, and R * Lines 2..M+1: Line i+1 describes FJ's ith milking interval withthree space-separated integers: starting_houri , ending_houri , and efficiencyi

Output

* Line 1: The maximum number of gallons of milk that Bessie can product in the N hours

Sample Input

12 4 2
1 2 8
10 12 19
3 6 24
7 10 31

Sample Output

43

題目分析:

輸入n,m,t,n表示一共可以擠奶的時間,m表示可以擠奶的次數,接下來m行代表擠奶時間以及奶量,t表示每擠一次奶需要休息的時間,求最大擠奶量。

程式碼:

#include<iostream>
#include<cstring>
#include<cstdio>
#include<queue>
#include<cmath>
#include<algorithm>
using namespace std;
int dp[10010];//dp[i]表示第i個時間段擠奶能夠得到的最大值
struct node
{
    int fr, ed, h;
}s[10010];

int cmp( node a, node b)
{
    if(a.fr==b.fr)
        return a.ed<b.ed;

    return a.fr<b.fr;
}

int main()
{
    int n, m, t;
    while(scanf("%d%d%d",&n,&m,&t)!=EOF)
    {
        for(int i=0;i<m;i++)
        {
            scanf("%d%d%d",&s[i].fr,&s[i].ed,&s[i].h);
           // s[i].ed+=t;
        }
        sort(s,s+m,cmp);

        for(int i=0;i<m;i++)
            dp[i]=s[i].h;
        for(int i=0;i<m;i++)
            for(int j=0;j<i;j++)
 //如果i區間的開始時間>=i-1個區間裡的有某個區間的結束時間+休息時間,比較。         
                if(s[i].fr>=s[j].ed+t)   
//第i個時間段擠奶的最大值 = 前 i – 1 個時間段擠奶最大值中的最大值 + 第i次產奶量。     
                     dp[i]=max(dp[i],dp[j]+s[i].h);

        int maxn=0;
        for(int i=0;i<m;i++)
            maxn=max(maxn,dp[i]);

        printf("%d\n",maxn);
    }
    return 0;
}

連結

定義dp[i]表示第i個時間段擠奶能夠得到的最大值,拆開來說,就是前面 i – 1個時間段任取0到i – 1個時間段擠奶,然後加上這個時間段(i)的產奶量之和。dp[i]滿足如下遞推關係:

第i個時間段擠奶的最大值 = 前 i – 1 個時間段擠奶最大值中的最大值 + 第i次產奶量。

注意此處的第i個時間段不等同於第i次。