poj 3190 Stall Reservations 贪心

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:
  • 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
Many answers are correct for each test dataset; a program will grade your answer.
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.
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.
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.
题意:

一些奶牛要在指定的时间内挤牛奶,而一个机器只能同时对一个奶牛工作。给你每头奶牛的指定时间的区间,问你最小需要多少机器,并且输出每头奶牛所用的机器序号。

按照每头奶牛挤牛奶的开始时间排序后,维护一个优先队列,按照奶牛的结束时间排序从小到大排序,每次比较队首元素中奶牛的结束时间和当前奶牛的开始时间,若大,则需要一台新机器,否则用队首的那台机器

#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<queue>
using namespace std;
struct p
{
    int x;
    int y;
    int z;
    friend bool operator<(p n1,p n2)//维护一个优先队列
    {
        return n1.y>n2.y;
    }
} a[50010];
bool cmp(p x,p y)
{
    if(x.x==y.x)
        return x.y<y.y;
    return x.x<y.x;//按照开始时间从小到大排序
}
int main()
{
    int t;
    int s[50010];
    while(~scanf("%d",&t))
    {
        memset(s,0,sizeof(s));
        for(int i=0; i<t; i++)
        {
            scanf("%d%d",&a[i].x,&a[i].y);
            a[i].z=i;//记录位置
        }
        sort(a,a+t,cmp);
        priority_queue<p>Q;
        Q.push(a[0]);
        s[a[0].z]=1;//记录使用的机器序号
        int sum=2;
        for(int i=1; i<t; i++)
        {
            if(Q.top().y>=a[i].x)
                s[a[i].z]=sum++;
            else
            {
                s[a[i].z]=s[Q.top().z];
                Q.pop();
            }
            Q.push(a[i]);
        }
        printf("%d\n",sum-1);
        for(int i=0; i<t; i++)
            printf("%d\n",s[i]);
    }
    return 0;
}



猜你喜欢

转载自blog.csdn.net/zch3210/article/details/70053268