链接:http://poj.org/problem?id=3190
Stall Reservations
Time Limit: 1000MS | Memory Limit: 65536K | |||
Total Submissions: 6645 | Accepted: 2401 | Special Judge |
Description
Oh those picky N (1 <= N <= 50,000) cows! They are so picky that each one will only be milked over some precise time interval A..B (1 <= A <= B <= 1,000,000), which includes both times A and B. Obviously, FJ must create a reservation system to determine which stall each cow can be assigned for her milking time. Of course, no cow will share such a private moment with other cows.
Help FJ by determining:
Help FJ by determining:
- The minimum number of stalls required in the barn so that each cow can have her private milking period
- An assignment of cows to these stalls over time
Input
Line 1: A single integer, N
Lines 2..N+1: Line i+1 describes cow i's milking interval with two space-separated integers.
Lines 2..N+1: Line i+1 describes cow i's milking interval with two space-separated integers.
Output
Line 1: The minimum number of stalls the barn must have.
Lines 2..N+1: Line i+1 describes the stall to which cow i will be assigned for her milking period.
Lines 2..N+1: Line i+1 describes the stall to which cow i will be assigned for her milking period.
Sample Input
5 1 10 2 4 3 6 5 8 4 7
Sample Output
4 1 2 3 2 4
Hint
Explanation of the sample:Here's a graphical schedule for this output:
Time 1 2 3 4 5 6 7 8 9 10 Stall 1 c1>>>>>>>>>>>>>>>>>>>>>>>>>>> Stall 2 .. c2>>>>>> c4>>>>>>>>> .. .. Stall 3 .. .. c3>>>>>>>>> .. .. .. .. Stall 4 .. .. .. c5>>>>>>>>> .. .. ..Other outputs using the same number of stalls are possible.
题意:N只牛,用挤奶器挤奶,时间为s-e,试计算最少用多少个挤奶器能挤完这n只牛?
思路:贪心,先按开始时间从小到大排序,这样能够保证不会有奶牛的挤奶时间在上一只前面,然后建立优先队列,按结束时间从小到大排序,然后依次向队列中加入n只奶牛,同时拿出一只奶牛,如果拿出的奶牛结束时间小于当前加入奶牛的开始时间,表示这两头奶牛可以共用一个挤奶器,反之不能
贪心思路比较容易想到,但是优先队列没有想到,看到别人用优先队列就恍然大悟了
代码:
#include<stdio.h>
#include<stdlib.h>
#include<iostream>
#include<queue>
#include<algorithm>
using namespace std;
const int maxn = 50000 + 10;
struct node {
int s;
int e;
int k;
};
int n;
node cow[maxn];
int vis[maxn];//挤奶器
bool cmp1(node a, node b) {
if (a.s == b.s)
return a.e < b.e;
else return a.s < b.s;
}
bool operator < (const node &a, const node &b)//产奶结束越早的越优先
{
if (a.e == b.e)
return a.s>b.s;
return a.e>b.e;
}
int main() {
while (scanf("%d", &n) != EOF) {
memset(vis, 0, sizeof(vis));
for (int i = 1; i <= n;i++) {
scanf("%d %d", &cow[i].s, &cow[i].e);
cow[i].k = i;
}
sort(cow + 1, cow + n + 1, cmp1);
priority_queue<node>Q;//按结束时间排序
Q.push(cow[1]);
vis[cow[1].k] = 1;
int j = 1;
for (int i = 2; i <= n;i++) {
node neww = Q.top();
if (cow[i].s > neww.e) {//可以同用一个挤奶器
vis[cow[i].k] = vis[neww.k];
Q.pop();
}
else {//不能同用一个挤奶器
j++;
vis[cow[i].k] = j;
}
Q.push(cow[i]);
}
cout << j << endl;
for (int i = 1; i <= n; i++)cout << vis[i] << endl;
}
return 0;
}