畜栏预定(贪心)

传送门:111. 畜栏预定 - AcWing题库

思路:给每一头奶牛做标记后按照开始时间从小到大排序,维护一个畜栏结束时间小根堆,遍历每头牛,开始时间小于等于堆顶结束时间就新开一个畜栏后压入堆,否则就更新堆顶元素。

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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值