poj3190 区间贪心 + STL

题意:n头任性的牛,每头牛都要在自己的时间段里挤奶,问最少用多少个挤奶槽并输出每头牛所在的挤奶槽的编号(从1开始)

思路:目标明确,求最少用多少奶槽,并输出如何分配,明显区间贪心,找贪心的方向,就是对时间的最末端进行贪心。

简单来说,先把奶牛们的时间输入并按开始时间进行排序,然后依次把有序的时间段都放入堆中,在此过程中每次取出堆中末端时间最小的和当前放入堆的时间段进行比较,如果能放到同一个槽就放,反之开辟一个新槽,最终得出结果。

代码:

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

using namespace std;
struct Node{
    int l;
    int r;
    int id;   //第几头牛
    int rk;   //第几个槽
};
Node a[51000];
int n;
struct cmp{
    bool operator()(Node &a,Node &b)
    {
        if(a.r != b.r)
            return a.r > b.r;
        else
            return a.l > b.l;
    }
};
int cmp1(Node a,Node b)
{
    if(a.l != b.l)
        return a.l < b.l;
    return a.r < b.r;
}
int cmp2(Node a,Node b)
{
    return a.id < b.id;
}
void input()
{
    for(int i = 0 ; i < n ; i++){
        cin >> a[i].l >> a[i].r;
        a[i].id = i;
    }

}
void solve()
{
    int ans = 1;
    sort(a,a+n,cmp1);
    priority_queue <Node , vector<Node> , cmp > q;
    a[0].rk = 1;
    q.push(a[0]);
    for(int i = 1 ; i < n ; i++)
    {
        Node t = q.top();

        if( a[i].l > q.top().r )
        {
            a[i].rk = t.rk;
            q.pop();
        }
        else{
            a[i].rk = ++ans;
        }
        q.push(a[i]);

    }
    sort(a,a+n,cmp2);
    cout << ans <<endl;
    for(int i = 0 ; i < n ; i++)
        cout<< a[i].rk <<endl;
}
int main()
{
    #ifdef H_R
        freopen("in.txt","r",stdin);
    #endif // H_R
    cin.tie(false);
    ios::sync_with_stdio(false);
    while(cin>>n)
    {
        input();
        solve();
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值