有 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≤50000,
1≤A,B≤1000000
输入样例:
5
1 10
2 4
3 6
5 8
4 7
输出样例:
4
1
2
3
2
4
#include<bits/stdc++.h>
using namespace std;
typedef pair<int,int> PII;
const int N=50010;
int n;
int id[N];
pair<PII,int> cows[N];
int 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 <PII,vector<PII>,greater<PII>>heap; //建立小根堆;
for(int i=0;i<n;i++) { // 贪心,区间组合问题;
if(heap.empty()||heap.top().first >=cows[i].first.first){ // 建立新畜栏;
PII stall ={ cows[i].first.second,heap.size()};
id[cows[i].second]=stall.second; // 记录这头牛儿在哪个畜栏吃草;
heap.push(stall); // 将新建立的畜栏进堆;
}
else { // 如果这头牛儿可以在其他畜栏吃草
PII stall=heap.top();
heap.pop();
stall.first=cows[i].first.second;//将该畜栏的右端点更新为该头牛儿的吃草结束时间;
id[cows[i].second]=stall.second; //记录这头牛儿在哪个畜栏吃草;
heap.push(stall); // 将更新后的该畜栏入堆;
}
}
cout << heap.size() <<endl;
for(int i=0;i<n;i++) cout << id[i]+1 << endl;
return 0;
}
//妙用pair + 数组的方式记录每头牛儿吃草的畜栏号