畜栏预定(贪心)

有N头牛在畜栏中吃草。

每个畜栏在同一时间段只能提供给一头牛吃草,所以可能会需要多个畜栏。

给定N头牛和每头牛开始吃草的时间A以及结束吃草的时间B,每头牛在[A,B]这一时间段内都会一直吃草。

当两头牛的吃草区间存在交集时(包括端点),这两头牛不能被安排在同一个畜栏吃草。

求需要的最小畜栏数目和每头牛对应的畜栏方案。

输入格式

第1行:输入一个整数N。

第2..N+1行:第i+1行输入第i头牛的开始吃草时间A以及结束吃草时间B,数之间用空格隔开。

输出格式

第1行:输入一个整数,代表所需最小畜栏数。

第2..N+1行:第i+1行输入第i头牛被安排到的畜栏编号,编号从1开始,只要方案合法即可。

数据范围

1≤N≤500001≤N≤50000,
1≤A,B≤10000001≤A,B≤1000000

输入样例:

5
1 10
2 4
3 6
5 8
4 7

输出样例:

4
1
2
3
2
4

AC代码: 

#include <bits/stdc++.h>
using namespace std;
#define int long long

const int maxn=50000+10;
pair<pair<int,int>,int>cows[maxn];

int id[maxn];
int n;
signed main(){
    cin>>n;
    for(int i=0;i<n;i++){
        cin>>cows[i].first.first>>cows[i].first.second;
        cows[i].second=i;
    }
    
    sort(cows,cows+n);
    
    priority_queue<pair<int,int>,vector<pair<int,int>>,greater<pair<int,int>> >heap;
    
    for(int i=0;i<n;i++){
        auto cow=cows[i].first;
        if(heap.empty()||heap.top().first>=cow.first){
            pair<int,int>stall={cow.second,heap.size()+1};
            id[cows[i].second]=stall.second;
            heap.push(stall);
        }
        else{
            auto stall=heap.top();
            heap.pop();
            stall.first=cow.second;
            id[cows[i].second]=stall.second;
            heap.push(stall);
        }
    }
    
    
    cout<<heap.size()<<endl;
    
    for(int i=0;i<n;i++)
    cout<<id[i]<<endl;
    
    
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值