题意:

有n头奶牛,每头奶牛喝牛奶的时候都不愿意被打扰,告诉你每头奶牛开始喝牛奶和结束和牛奶的时间 a 和 b, 求至少需要多少个隔间,使每头奶牛喝牛奶的时间不相交

思路:

每头奶牛按照开始的时间​从小到大​排,每一次如果能安排进​最早​结束的隔间,则刷新此隔间的结束时间,​否则​开一个新的隔间 

奶牛用结构体存储开始

#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<queue>
#include<functional>
using namespace std;
const int maxn = 500005;
struct cow {
int start;
int end;
int num;
int id;
}cows[maxn];
bool operator < (const cow a, const cow b) {
return a.start<b.start;
}
bool cmp(cow a, cow b) {
return a.num < b.num;
}
int main() {
int N;
while (~scanf("%d", &N)){

for (int i = 0; i < N; i++) {
int a, b; scanf("%d%d", &a, &b);
cows[i].start = a;
cows[i].end = b;
cows[i].num = i+1;
}
sort(cows, cows + N);
int ans = 0;
priority_queue<pair<int, int>, vector<pair<int, int> >, greater<pair<int, int> > >q;
q.push(pair<int,int>(cows[0].end,++ans));
cows[0].id = ans;
for (int i = 1; i < N; i++) {
pair<int, int> p = q.top();//返回结束时间最早的
if (p.first < cows[i].start) {//如果可以安排的话,更新
q.pop();
cows[i].id = p.second;
q.push(pair<int, int>(cows[i].end, p.second));
}
else{//放入新的
q.push(pair<int, int>(cows[i].end, ++ans));
cows[i].id = ans;

}
}
cout << ans << endl;
sort(cows, cows + N, cmp);//按照原来输入的顺序输出
for (int i = 0; i < N; i++) {
cout << cows[i].id << endl;
}
}
}