poj3190

对牛按照milk的开始时间排序。
对优先队列里牛的milk的结束时间排序,结束时间最早的作为que.top()和牛i做对比,如果牛i的开始时间大于(因为文中说include A和B,所以不能取等号。)que.top()的结束时间,那么将该牛的牛栏(stall)设为与que.top()相同的牛栏,同时que.pop();否则新建一个牛栏,将牛i的牛栏设为该新建的牛栏。

//1492k, 219ms
#include <iostream>
#include <queue>
#include <algorithm>

using namespace std;

const int MAX_N = 50005;

struct Interval {
    int from;
    int to;
    int pos;

    //优先队列里结束时间最早的优先
    bool operator < (const Interval &a) const {
        if(to == a.to) return from > a.from;//如果结束时间相同,则开始时间早的优先 
        else           return to > a.to;
    } 

}interval[MAX_N];

priority_queue<Interval> que;

int n, stall[MAX_N];

//对牛的milk时间进行排序,开始时间早的放前面。 
bool cmp(Interval a, Interval b) {
    if(a.from == b.from) return a.to < b.to;
    else                 return a.from < b.from;
} 

int main() {

    freopen("in.txt", "r", stdin);

    while(~scanf("%d", &n)) {
        for(int i=0; i<n; i++) {
            scanf("%d%d", &interval[i].from, &interval[i].to);
            interval[i].pos = i;
        }

        sort(interval, interval+n, cmp);

        int ans=1;
        stall[interval[0].pos] = 1;
        que.push(interval[0]);
        for(int i=1; i<n; i++) {
            if(!que.empty() && que.top().to<interval[i].from) {
                stall[interval[i].pos] = stall[que.top().pos];
                que.pop();
            } else {
                ans++;
                stall[interval[i].pos] = ans;
            }
            que.push(interval[i]);
        }

        printf("%d\n", ans);
        for(int i=0; i<n; i++)
            printf("%d\n", stall[i]);

        while(!que.empty()) que.pop();
    }

    fclose(stdin);

    return 0;
}
posted @ 2017-02-14 15:33  StevenLuke  阅读(78)  评论(0编辑  收藏  举报