[USACO06FEB]摊位预订Stall Reservations {优先队列+贪心}

题目

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]); 
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值