poj 3190

题意:

每头奶牛拥有自己的可以挤奶的时间。且,每头牛都必须挤奶,而他们又不愿意在一间房,问最少需要造多少间房。

可以用贪心做,依据开始时间排序。依次放奶牛(开始时间最小),若所有房间都没空,那么就再造一间房。

判断房间状态,用for循环会超时,可以使用优先队列,队列排序是房间空的越早越排前。




#include<cstdio>
#include<algorithm>
#include<queue>
using namespace std;
const int maxn = 50000 + 5;
const int inf = 1e9;
struct node
{
    int beg, en, id;
    bool operator < (const node& a) const
    {
        return beg < a.beg;
    }
}cows[maxn], stall[maxn];
struct node1
{
    int en, id;
    node1(int x, int y):en(x), id(y){}
    bool operator<(const node1& a) const
    {
        return en > a.en;
    }
};
int p[maxn];
int main()
{
    int n;
    while(scanf("%d", &n) == 1)
    {
        priority_queue<node1> pq;
        for(int i = 0; i < n; i++)
        {
            scanf("%d%d", &cows[i].beg, &cows[i].en);
            cows[i].id = i;
        }
        sort(cows, cows + n);
        pq.push(node1(cows[0].en, 0));//当前房间最早什么时候空和房间的号
        p[cows[0].id] = 0;
        int cnt = 1;
        for(int i = 1; i < n; i++)
        {
            node1 t = pq.top();
            if(cows[i].beg > t.en)
            {
                //printf("%d %d\n", i, cnt);
                pq.pop();
                pq.push(node1(cows[i].en, t.id));
                p[cows[i].id] = t.id;
            }
            else
            {
                pq.push(node1(cows[i].en, cnt));
                p[cows[i].id] = cnt++;
            }
        }
        printf("%d\n", cnt);
        for(int i = 0; i < n; i++)
        {
            printf("%d\n", p[i] + 1);
        }
    }
    return 0;
}




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章