POJ_3190_Stall Reservations

来源:互联网 发布:淘宝预售如何合并付款 编辑:程序博客网 时间:2024/06/10 18:15

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:
  • 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.

Hint

Explanation of the sample:

Here's a graphical schedule for this output:

Time     1  2  3  4  5  6  7  8  9 10Stall 1 c1>>>>>>>>>>>>>>>>>>>>>>>>>>>Stall 2 .. c2>>>>>> c4>>>>>>>>> .. ..Stall 3 .. .. c3>>>>>>>>> .. .. .. ..Stall 4 .. .. .. c5>>>>>>>>> .. .. ..
Other outputs using the same number of stalls are possible.

====================================================================================================================================

题意是农夫有N头奶牛,每头奶牛有自己的产奶时间A到B,每头牛产奶时必须单独为它安排一间畜栏,不得同时共用一间,
要求根据,每头牛的产奶时间,安排一个合理的方案使得使用畜栏数最少。

明显要先处理产奶时间靠前并且结束时间靠前的奶牛,这样才能使后面的奶牛接着使用同一畜栏。
对其结构体排序,按起始时间靠前排前面,相同按结束时间靠前排前面。

这样从0~N找是只要判断该奶牛的起始时间是否比前面每个畜栏的最小的终止时间大,如果大的话,就可以安排在其后面产奶,并且更新该畜栏的终止时间。
如果小的话,则必须新开一间畜栏。

因为一直要找最小值,考虑使用后优先队列(priority_queue),结束时间小的优先级高。这样比较方便找最小值。

具体代码如下:
#include<queue>#include<math.h>#include<stdio.h>#include<string.h>#include<algorithm>using namespace std;struct node{    int x,y;    int no;    int ss;    friend bool operator< (node n1, node n2)//定义优先级    {        return n1.y > n2.y;    }} p[50050];bool cmp1 (node a,node b){    if (a.x==a.y) return a.y<b.y;    else return a.x<b.x;}bool cmp2 (node a,node b){    return a.ss<b.ss;}int main(){    int n,i,tag=0,co=0;    scanf ("%d",&n);    for (i=0;i<n;i++){        scanf ("%d%d",&p[i].x,&p[i].y);p[i].ss=i;    }    sort (p,p+n,cmp1);tag=p[0].x;    priority_queue <node> que;//    for (i=0;i<n;i++)//        printf ("%d:%d %d\n",i,p[i].x,p[i].y);    for (i=0;i<n;i++){        if (tag>=p[i].x){            co++;p[i].no=co;            que.push(p[i]);            tag=que.top().y;        }        else {            p[i].no=que.top().no;            que.pop();            que.push(p[i]);            tag=que.top().y;        }    }//    while (!que.empty())//    {//        printf ("%d ",que.top().y);//        que.pop();//    }    printf ("%d\n",co);    sort (p,p+n,cmp2);    for (i=0;i<n;i++)        printf("%d\n",p[i].no);    return0;}
















0 0
原创粉丝点击