1. 程式人生 > >暑假訓練 Stall Reservations POJ

暑假訓練 Stall Reservations POJ

題目描述: 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.

code:

#include<cstdio>
#include<queue>
#include<algorithm>
#define maxn 50005
using namespace std;

struct cow
{
    int beginn;
    int endn;
    int posi;
    int times;
    bool operator <(const cow&a)const
    {
        if(endn == a.endn)
            return beginn < a.beginn;
        return endn > a.endn;
    }
}cows[maxn];

bool cmp(cow a, cow b)
{
    if(a.beginn == b.beginn)
        return a.endn < b.endn;
    else return a.beginn < b.beginn;
}

priority_queue<cow>Q;

int main()
{
    int n, num = 0;
    scanf("%d", &n);
    for(int i = 0; i < n; i++)
    {
        scanf("%d%d", &cows[i].beginn, &cows[i].endn);
        cows[i].posi = i;
    }
    sort(cows, cows+n, cmp);
    cows[cows[0].posi].times = 1;
    Q.push(cows[0]);
    num++;
    for(int i = 1; i < n; i++)
    {
        if(!Q.empty() && Q.top().endn < cows[i].beginn)
        {
            cows[cows[i].posi].times = cows[Q.top().posi].times;
            Q.pop();
        }
        else
        {
            num++;
            cows[cows[i].posi].times = num;
        }
        Q.push(cows[i]);
    }
    printf("%d\n", num);
    for(int i = 0; i < n; i++)
    {
        printf("%d\n", cows[i].times);
    }
    while(!Q.empty())Q.pop();
    return 0;
}

這個題目就水的很舒服了,主要就是注意儲存下開始在陣列中的位置,在排序後按照原順序輸出,最初不是用優先佇列寫的,勉強能過,用優先佇列後就可以優化到200ms左右了,開心。。。