POJ 3190 Stall Reservations (优先队列)C++

Stall Reservations
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 7646   Accepted: 2710   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:
  • 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.
 
 
这道大水题真的坑,不少人想的都是贪心,背包问题。比赛时候甚至队友讨论过树状数组。。。。。。。
比赛结束鹏哥说C题E题都是水题,E题优先队列。   喵喵喵???
仔细一想真的是啊。根本没往这方面想过!!
每次看完题解都是这么简单怎么没想出来,允悲。。。
 
 
 
这道题是修改了队列的优先级,因为在同一槽中要下一只牛的话, 当前r值必须小于l值。所以优先级r值优先。
所以本题的难点就在于,怎样处理当前槽,怎样构造队列优先级!!
#include<iostream>
#include<cstdio>
#include<queue>
#include<algorithm>
using namespace std;
struct node
{
    int l,r,n;
    bool operator <(const node &b)const
    {
        return r>b.r||(r==b.r&&l>b.l);
    }
}a[50005];
priority_queue <node> q;
int u[50005];
bool cmp(node a,node b)
{

    return a.l<b.l||(a.l==b.l&&a.r<b.r);
}
int main()
{
    int n,m;
    while(~scanf("%d",&n))
    {
        int ans=1;
        for(int i=1;i<=n;i++)
        {
            scanf("%d%d",&a[i].l,&a[i].r);
            a[i].n=i;
        }
        sort(a+1,a+n+1,cmp);
        q.push(a[1]);
        u[a[1].n]=1;

        for(int i=2;i<=n;i++)
        {
            if(!q.empty()&&q.top().r<a[i].l){
                u[a[i].n]=u[q.top().n];
                q.pop();
            }
            else{
                ans++;
                u[a[i].n]=ans;
            }
            q.push(a[i]);
        }
        printf("%d\n",ans);
        for(int i =1;i<=n;i++){
            printf("%d\n",u[i]);
        }
        while(!q.empty())   // 尤其重要,排空队列
            q.pop();
    }
}

  

posted @ 2017-08-24 22:04  会飞的雅蠛蝶  阅读(199)  评论(0编辑  收藏  举报