簡單dp算法——Milking Time

C - Milking Time
Crawling in process... Crawling failed Time Limit:1000MS     Memory Limit:65536KB     64bit IO Format:%lld & %llu

Description

Input

Output

Sample Input

Sample Output

Hint

Description

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

題意

一個奶牛在0~N時間段內可被取奶,每次擠奶以後必須休息至少R分鐘才能下次繼續擠奶。有M次可以擠奶的時間段,每次取奶對應三個值:開始時間、結束時間、效率值,每次擠奶的過程不能中斷。求出最大效率值。

解法

首先按照結束時間從小到大排序(按照結束時間排序方便後邊的dp);dp[i]表示第i個擠奶時間段後,效率最大值。

代碼實現:

#include <iostream>
#include <cstdio>
#include <queue>
#include <vector>
#include <map>
#include <cmath>
#include <algorithm>

using namespace std;

struct node                      // 記錄每次擠奶的參數;
{
    int sta;
    int End;
    int val;
};

bool cmp( node a, node b )
{
    return a.End < b.End;
}

int main()
{
    int N, M, R;
    cin >> N >> M >> R;
    node m[M];
    int i, j;
    for( i=0; i<M; i++ )
    {
        cin >> m[i].sta >> m[i].End >> m[i].val;
    }
    sort( m, m+M, cmp );                        // 根據每次擠奶的結束時間排序;
    int dp[M];
    int sum = 0;                                // 最大奶量;
    for( i=0; i<M; i++ )
    {
        dp[i] = m[i].val;
        for( j=0; j<i; j++)
        {
            if( m[j].End+R <= m[i].sta )         // 如果在本次擠奶之前還能擠奶,則到這次擠奶最大奶量爲
                                                 // max(本次奶量, 本次奶量 + 之前最大奶量);
                dp[i] = max( dp[i], m[i].val + dp[j] );
        }
        if( dp[i] > sum )
            sum = dp[i];
    }
    cout << sum << endl;
    return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章