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
問題連結: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;
}