题目
http://poj.org/problem?id=3190
https://www.luogu.org/problemnew/show/P2859
解题思路
正常的贪心(即先排序,每次的寻找还要扫描一遍每一个畜栏的情况)时间复杂度为 O(n2) O ( n 2 ) 。我们可以用一个小根堆(优先队列/ STLpriorityqueue S T L p r i o r i t y q u e u e )维护每个畜栏最后一头牛结束吃草的时间,尝试把当前的牛安排在堆顶(结束时间最早)的畜栏中,时间复杂度为 O(n log n) O ( n l o g n ) 。
代码
#include<cstdio>
#include<queue>
#include<vector>
#include<algorithm>
using namespace std;
struct nod{
int x,y,ne;
}a[50010];
struct node{
int w;
bool operator <(const node &g) const{
return a[w].y>a[g.w].y;
}
};
priority_queue< node,vector<node> >que;
int n,belong[50010],len;
bool cmp(nod x,nod y){return x.x<y.x;}
int main()
{
scanf("%d",&n);
for (int i=1;i<=n;i++) scanf("%d%d",&a[i].x,&a[i].y),a[i].ne=i;
sort(a+1,a+n+1,cmp);
for (int i=1;i<=n;i++)
{
node k; k.w=i;
if (!que.empty()){
node z=que.top();
if (a[z.w].y>=a[i].x){
que.push(k);
belong[a[i].ne]=++len;
} else {
que.pop();
que.push(k);
belong[a[i].ne]=belong[a[z.w].ne];
}
} else {
que.push(k);
belong[a[i].ne]=++len;
}
}
printf("%d\n",len);
for (int i=1;i<=n;i++)
printf("%d\n",belong[i]);
}