题目链接
http://poj.org/problem?id=3190
分析
贪心,先将牛按开始吃草的时间升序排序。
依次考虑每头牛,若其能加入某个已存在的畜栏(即其开始时间晚于该畜栏中上一头牛的结束时间),则加入;
否则新建一个畜栏供其使用。
枚举下一头牛在安置时可能的情况,会发现这样做最优。
AC代码
#include <cstdio>
#include <algorithm>
#include <queue>
using namespace std;
inline int read() {
int num = 0;
char c = getchar();
while (c < '0' || c > '9') c = getchar();
while (c >= '0' && c <= '9')
num = num * 10 + c - '0', c = getchar();
return num;
}
const int maxn = 5e4 + 5;
struct Cow {
int id, l, r;
bool operator < (const Cow& rhs) const {
return l < rhs.l;
}
} cow[maxn];
struct Stall {
int id, last;
bool operator < (const Stall& rhs) const {
return last > rhs.last;
}
};
int ans[maxn], tot;
priority_queue<Stall> q;
int main() {
int n = read();
for (int i = 1; i <= n; ++i)
cow[i].id = i, cow[i].l = read(), cow[i].r = read();
sort(cow + 1, cow + n + 1);
for (int i = 1; i <= n; ++i) {
if (q.empty() || cow[i].l <= q.top().last) {
ans[cow[i].id] = ++tot;
q.push((Stall){tot, cow[i].r});
} else {
ans[cow[i].id] = q.top().id;
q.pop();
q.push((Stall){ans[cow[i].id], cow[i].r});
}
}
printf("%d\n", tot);
for (int i = 1; i <= n; ++i) printf("%d\n", ans[i]);
return 0;
}