poj 3190 Stall Reservations

 

原题链接:http://poj.org/problem?id=3190

题目大意: 一些很挑剔的奶牛需要在特定的时间内挤奶,一个挤奶棚每次只能有一头奶牛挤奶,求出最少需要的挤奶棚的数量;

思路:贪心+优先队列; 先用开始挤奶的时间顺序排序,然后再按照结束时间早的顺序存到优先队列中; 这样每次判断一下当前是否有空的挤奶棚可以用就行了,如果有直接用,没有的话奶棚数量加一;

代码:

复制代码
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <string>
#include <stack>
#include <queue>
#include <cmath>
#define ll long long
#define pi 3.1415927
using namespace std;
struct node {
int a,b,c;
}a[50005];
bool cmp (node x, node y)
{
    if (x.a!=y.a)
        return x.a<y.a;
    return x.b<y.b;
}
struct cow{
int i,e;
friend bool operator < (cow x, cow y)
    {
    return x.e>y.e;
    }
}b;
priority_queue <cow> q ;
int c[50005];
int main ()
{
    int n,m,i,t,j,k,sum=0;
    scanf("%d",&n);
    for (i=0;i<n;++i){
        scanf("%d %d",&a[i].a,&a[i].b);
        a[i].c=i;
        ///a,b 存挤奶的开始和结束时间   c存第几头奶牛
    }
    sort(a,a+n,cmp);
    int p=1;
    sum=0;
    for (i=0;i<n;++i)
    {
        if(q.empty())
        {
            c[a[i].c]=p++;
            sum++;
            b.i=a[i].c; b.e=a[i].b;
            q.push( b );
            continue;
        }

        if (q.top().e < a[i].a )  
        ///如果当前奶牛的开始时间大于队列顶部元素的结束时间代表有空的挤奶棚可以用
        {
            c[a[i].c] = c[ q.top().i ];
            q.pop();
            b.i=a[i].c;  b.e=a[i].b;
            q.push( b );
        }
        else
        {
            c[a[i].c]=p++;
            sum++;
            b.i=a[i].c;  b.e=a[i].b;
            q.push( b );
        }
    }
    printf("%d\n",sum);
    for (i=0;i<n;++i)
        printf("%d\n",c[i]);

    return 0;
}
复制代码

 

posted @   blowhail  阅读(145)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· [AI/GPT/综述] AI Agent的设计模式综述
Live2D
欢迎阅读『poj 3190 Stall Reservations』
点击右上角即可分享
微信分享提示