洛谷P2859 摊位预定 - 贪心

贪心常见操作 排序 堆 微扰
区间贪心常按左右端点排序,一般左居多
因为按左排序后,对于第i个区间 其后区间一定左端点在其后
不用考虑第i个区间前面是否能插一个小区间了
用堆做这题实际上是加速找棚的过程

#include <algorithm>
#include <iostream>
#include <cstdio>
#include <queue>
using namespace std;
#define debug(x) cerr << #x << "=" << x << endl;
const int INF = 0x7fffffff - 10;
const int MAXN = 50010;
int n,maxt,size,ans,ansp[MAXN];
struct ade{
    int l,r,id;
}c[50010];
struct stall{
    int tim,id;
    bool operator < (const stall &temp_opera) const {
        return temp_opera.tim < tim;
    }
};
priority_queue <stall> q;
bool cmp(ade a, ade b) {
    return a.l < b.l;
}
int main() {
    scanf("%d", &n); 
    for(int i=1; i<=n; i++) {
        scanf("%d %d", &c[i].l, &c[i].r);
        c[i].id = i;
    }
    sort(c+1,c+n+1,cmp);
    q.push((stall){c[1].r,1});
    ans = 1;
    ansp[c[1].id] = 1;
    for(int i=2; i<=n; i++) {
        stall x = q.top();
        if(c[i].l <= x.tim) {
            ans++;
            q.push((stall){c[i].r, ans});
            ansp[c[i].id] = ans;
        } else {
            q.push((stall){c[i].r, q.top().id});
            ansp[c[i].id] = q.top().id;
            q.pop();
        }
    }
    printf("%d\n",ans);
    for(int i=1; i<=n; i++) 
        printf("%d\n",ansp[i]);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/Fantasy_World/article/details/81609113