思路:给每一头奶牛做标记后按照开始时间从小到大排序,维护一个畜栏结束时间小根堆,遍历每头牛,开始时间小于等于堆顶结束时间就新开一个畜栏后压入堆,否则就更新堆顶元素。
O(n^2)正确但超时代码:
#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
#include <map>
#define x first
#define y second
using namespace std;
const int N=5e4+10;
typedef pair<int,int>PII;
int n;
pair<PII, int> a[N];
int s[N];
int cnt;
int d[N];
int main()
{
scanf("%d",&n);
int ans=0;
for(int i=1;i<=n;i++)
{
scanf("%d%d",&a[i].x.x,&a[i].x.y);
a[i].y=i;
}
sort(a+1,a+n+1);
for(int i=1;i<=n;i++)
{
int flag=0;
int k=0;
for(int j=1;j<=cnt;j++)
{
if(s[j]<a[i].x.x&&s[j]>=s[k])
{
flag=1;
k=j;
}
}
if(!flag)
{
s[++cnt]=a[i].x.y;
d[a[i].y]=cnt;
}else
{
s[k]=a[i].x.y;
d[a[i].y]=k;
}
}
printf("%d\n",cnt);
for(int i=1;i<=n;i++)
printf("%d\n",d[i]);
return 0;
}
堆优化代码:
#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
#include <map>
#define x first
#define y second
using namespace std;
const int N=5e4+10;
typedef pair<int,int>PII;
int n;
pair<PII, int> a[N];
int s[N];
int cnt;
int id[N];
int main()
{
scanf("%d",&n);
int ans=0;
for(int i=1;i<=n;i++)
{
scanf("%d%d",&a[i].x.x,&a[i].x.y);
a[i].y=i;
}
sort(a+1,a+n+1);
priority_queue<PII, vector<PII>, greater<PII>> heap;
for(int i=1;i<=n;i++)
{
if(heap.empty()||heap.top().x>=a[i].x.x)
{
PII stall={a[i].x.y,heap.size()+1};
id[a[i].y]=stall.y;
heap.push(stall);
}else
{
auto stall=heap.top();heap.pop();
stall.x=a[i].x.y;
id[a[i].y]=stall.y;
heap.push(stall);
}
}
cout<<heap.size()<<endl;
for(int i=1;i<=n;i++)
printf("%d\n",id[i]);
return 0;
}