StallReservations POJ-3190 [贪心-其他:优先队列]

贪心-其他:优先队列

原题StallReservations POJ3190

中国话:给出N个区间,将其不重叠地放在数轴上,至少需要几个数轴? [1, 2],[2, 3]算作重叠

思路:按照奶牛挤奶的开始时间升序排列,牛栏按照使用结束时间小的优先,放在优先队列中

//
//  StallReservations_POJ3190.cpp
//  workspace
//
//  Created by PDP11 on 2021/3/26.
//
//  特别注意!!!
//  对于自定义类型的优先队列,即使重载了小于比较,但默认还是大顶堆(大的优先)
//  注意重载小于号时返回 end>b.end 即可实现大的优先!!!


#include<iostream>
#include<cstdio>
#include<queue>
#include<vector>
#include<algorithm>

using namespace std;
const int maxn=50005;

struct code{
    int cnt,end;
    //  特别注意!!!
    //  对于自定义类型的优先队列,即使重载了小于比较,但默认还是大顶堆(大的优先)
    //  注意重载小于号时返回 end>b.end 即可实现大的优先!!!
    bool operator< (const code &b) const {
        return end>b.end;
    }
    code(int c=0,int e=0){
        cnt=c;end=e;
    }
};
priority_queue<code, vector<code> > pque;

struct cow{
    int beg,end;
    int index;
    bool operator< (const cow &b) const {
        return beg<b.beg;
    }
};
cow cows[maxn];
cow sortcows[maxn];

int main(){
#ifndef ONLINE_JUDGE
    freopen("input.txt","r",stdin);
    freopen("output.txt","w",stdout);
#endif
    
    int n;
    cin>>n;
    for(int i=0; i<n; i++){
        scanf("%d%d", &cows[i].beg, &cows[i].end);
        sortcows[i]=cows[i];
        sortcows[i].index=i;
    }
    sort(sortcows,sortcows+n);
    
    int time=1;
    code c(time,0);
    pque.push(c);
    for(int i=0; i<n; i++){
        code co=pque.top();pque.pop();
        if(co.end<sortcows[i].beg){
            co.end=sortcows[i].end;
            cows[sortcows[i].index].index=co.cnt;
        }
        else{
            code newco(++time,sortcows[i].end);
            cows[sortcows[i].index].index=newco.cnt;
            pque.push(newco);
        }
        pque.push(co);
    }
    cout << time << endl;
    for(int i=0; i<n; i++) printf("%d\n", cows[i].index);

#ifndef ONLINE_JUDGE
    fclose(stdin);
    fclose(stdout);
#endif
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值