题意可以去洛谷上看
https://www.luogu.org/problem/show?pid=2859
我们首先想,不同奶牛使用同一台的时间,需要在不冲突的情况下尽量接近,使每台机器搁置时间最短,最后总机器数量应该是最小的
我们需要一个动态的数据结构,能够找到可使用时间最早的机器,并且在另一头奶牛接手这台机器的时候,需要弹出这台机器曾经的可使用时间,而且还要logn的复杂度,那堆应该是最适合的
在这之间,我们先根据每头牛开始使用的时间进行从小到大的排序,使用小根堆存储每台机器的可使用时间,这个时间取决于最后使用这台机器的奶牛。每次加入新的元素时,判断其起始时间和堆顶时间,若起始时间小于等于堆顶时间,则需要加一台机器;否则,就接着使用这台机器,这意味着弹出堆顶。
然后需要注意的是这个地方。。。
ansp[c[1].id] = 1;
一开始我们设定起始时间最靠前的牛的机器是1,但是因为已经排序过了,所以下标是c[1].id
如果不需要打印方案的话,这题应该用差分来做的
我们令每头牛所占的区间都加上1,最后输出一个最高值就可以了,因为题目求的,其实是在某一个时刻,同时使用机器的奶牛最高数量。但是这样复杂度太高,因为对区间刷来刷去确实是很费事,可以考虑差分+前缀和来简化这个操作
具体来说,就是a[L] + 1, a[R + 1] - 1,这样,我们若要求a[L + 2]的值,只需要求1 ~ L + 2的前缀和,但是没有办法打印方案。
//不能打印方案的版本
#include <algorithm>
#include <iostream>
#include <cstdio>
using namespace std;
#define debug(x) cerr << #x << "=" << x << endl;
int n,maxt,size,ans;
int ansp[1000010];
struct ade{
int a,b,id;
}c[50010];
const int INF = 0x7fffffff - 10;
int main() {
cin >> n;
for(int i=1; i<=n; i++) {
cin >> c[i].a >> c[i].b;
c[i].id = i;
ansp[c[i].a]++;
ansp[c[i].b + 1]--;
maxt = max(maxt, c[i].b);
}
for(int i=1; i<=maxt; i++) {
size += ansp[i];
ans = max(ans,size);
}
cout << ans;
return 0;
}
//可以打印方案
#include <algorithm>
#include <iostream>
#include <cstdio>
#include <queue>
using namespace std;
#define debug(x) cerr << #x << "=" << x << endl;
const int INF = 0x7fffffff - 10;
const int MAXN = 50010;
int n,maxt,size,ans,ansp[MAXN];
struct ade{
int l,r,id;
}c[50010];
struct stall{
int tim,id;
bool operator < (const stall &temp_opera) const {
return temp_opera.tim < tim;
}
};
priority_queue <stall> q;
bool cmp(ade a, ade b) {
return a.l < b.l;
}
int main() {
scanf("%d", &n);
for(int i=1; i<=n; i++) {
scanf("%d %d", &c[i].l, &c[i].r);
c[i].id = i;
}
sort(c+1,c+n+1,cmp);
q.push((stall){c[1].r,1});
ans = 1;
ansp[c[1].id] = 1;
for(int i=2; i<=n; i++) {
stall x = q.top();
if(c[i].l <= x.tim) {
ans++;
q.push((stall){c[i].r, ans});
ansp[c[i].id] = ans;
} else {
q.push((stall){c[i].r, q.top().id});
ansp[c[i].id] = q.top().id;
q.pop();
}
}
printf("%d\n",ans);
for(int i=1; i<=n; i++)
printf("%d\n",ansp[i]);
return 0;
}