POJ3190 - 优先队列 贪心

POJ3190

将所有牛从小到大排序然后用优先队列(小根堆)依次记录插入的牛的结束时间,如果插入牛时起始时间大于首元素,ans不增加并弹出首元素。

挺简单的。那么为什么我会写(水)这篇博客呢?

复制代码
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<queue>
#include<utility>
#include<vector>
#include<ctype.h>
using namespace std;
const int maxn=5e4+10;
inline int read()
{
    int w=0,x=0;char c=getchar();
    while(!isdigit(c))w|=c=='-',c=getchar();
    while(isdigit(c))x=(x<<3)+(x<<1)+(c^48),c=getchar();
    return w?-x:x;
}
pair<pair<int,int>,int> a[maxn];
int n,id[maxn];
int main()
{
    n=read();
    priority_queue<pair<int,int>,vector<pair<int,int> >,greater<pair<int,int> > > q;
    for(int i=1;i<=n;i++)
    {
        a[i].first.first=read(),a[i].first.second=read();
        a[i].second=i;
    }
    int ans=0,tmp;
    sort(a+1,a+1+n);
    for(int i=1;i<=n;i++)
    {
        if(q.empty() or q.top().first>=a[i].first.first)
            tmp=++ans;
        else
            tmp=q.top().second,q.pop();
        q.push(make_pair(a[i].first.second,tmp));
        id[a[i].second]=tmp;
    }
    printf("%d\n",ans);
    for(int i=1;i<=n;i++)
    printf("%d\n",id[i]);
    return 0;
}
/*
5
1 10
2 4
3 6
5 8
4 7
*/
复制代码

如果您勇于实践,您会发现这个代码tle了。初步判定是我pair套多了。因为您随便在其他博客扒一个代码都会过。

这是一个教训。

还有就是注意priority_queue的排序方式。

如果queue中没有元素而您用访问top的话会挂。

posted @   Star_Cried  阅读(176)  评论(0编辑  收藏  举报
编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 使用C#创建一个MCP客户端
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示