Bailian4144 畜欄保留問題【貪心】

4144:畜欄保留問題
總時間限制: 1000ms 內存限制: 65536kB
描述
農場有N頭牛,每頭牛會在一個特定的時間區間[A, B](包括A和B)在畜欄裏擠奶,且一個畜欄裏同時只能有一頭牛在擠奶。現在農場主希望知道最少幾個畜欄能滿足上述要求,並要求給出每頭牛被安排的方案。對於多種可行方案,主要輸出一種即可。

輸入
輸入的第一行包含一個整數N(1 ≤ N ≤ 50, 000),表示有N牛頭;接下來N行每行包含兩個數,分別表示這頭牛的擠奶時間[Ai, Bi](1 ≤ A≤ B ≤ 1, 000, 000)。
輸出
輸出的第一行包含一個整數,表示最少需要的畜欄數;接下來N行,第i+1行描述了第i頭牛所被分配的畜欄編號(從1開始)。
樣例輸入
5
1 10
2 4
3 6
5 8
4 7
樣例輸出
4
1
2
3
2
4

來源
http://poj.org/problem?id=3190

問題鏈接Bailian4144 畜欄保留問題
問題簡述:(略)
問題分析:這個題與參考鏈接是同一個題,參見參考鏈接。
程序說明:(略)
參考鏈接POJ3190 Stall Reservations【貪心】
題記:(略)

AC的C++語言程序如下:

/* POJ3190 Stall Reservations */

#include <iostream>
#include <algorithm>
#include <queue>
#include <stdio.h>

using namespace std;

const int N = 50000;
struct Cow {
    int start, end, no;
    bool operator < (const Cow& a) const { // 產奶結束早的越優先
        return (end != a.end) ? end > a.end : start > a.start;
    }
} cow[N], now;
int num[N];

// 貪心法處理順序
int cmp(Cow a, Cow b)
{
    return (a.start == b.start) ? a.end < b.end : a.start < b.start;
}

int main()
{
    int n;

    while(~scanf("%d", &n)) {
        for(int i=0; i<n; i++) {
            scanf("%d%d", &cow[i].start, &cow[i].end);
            cow[i].no = i;
        }

        sort(cow, cow + n, cmp);

        int k = 0;
        priority_queue<Cow> q;
        q.push(cow[0]);
        num[cow[0].no] = ++k;
        for(int i=1; i<n; i++) {
            now = q.top();
            if(cow[i].start > now.end) { // 共用擠奶器
                num[cow[i].no] = num[now.no];
                q.pop();
            } else
                num[cow[i].no] = ++k;
            q.push(cow[i]);
        }

        printf("%d\n", k);
        for(int i=0; i<n; i++)
            printf("%d\n", num[i]);
    }

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