POJ 3190 贪心

6 篇文章 0 订阅

POJ 3190

题意N 头牛在畜栏中吃草 ,每个畜栏在同一时间段只能给一头牛吃, 2 -4 和 4 - 9必须要两个畜栏,给N头牛吃草和结束吃草时间

求最小畜栏数和每头牛吃的栏编号

一开始写了个n^2 暴力去统计超时

然后我们想到要用小根堆(优先队列放负数) 去优化

那么时间复杂度就降为O(nlogn)然后就可以过了

#include <cstdio>
#include <queue>
#include <stack>
#include <map>
#include <sstream>
#include <iostream>
#include <algorithm>
#include <set>
#include <cmath>
#include <vector>
using namespace std;
const int MAX_N = 50024;
int ans[MAX_N],now[MAX_N];
struct node {
    int l,r,id;
    bool operator < (const node other) const {
        if(l==other.l) return r<other.r;
        return l < other.l;
    }
}arr[MAX_N];
priority_queue<pair<int ,int > > q;
int main(){
    int n,use = 0;
    while(scanf("%d",&n)!=EOF){
    while(!q.empty()) q.pop();
    use = 0;
    for(int i = 1;i<=n;++i)
    {
        scanf("%d%d",&arr[i].l,&arr[i].r);
        arr[i].id = i;
    }
    sort(arr+1,arr+1+n);
    for(int i = 1;i<=n;++i){
    if(!q.empty()){
    int top = -q.top().first;
    int id = q.top().second;
    //cout << " top = " << top <<endl;
    //cout << "arr[i].l = " <<arr[i].l << endl;
    while(top<arr[i].l){
        now[ans[id]] = 0;
        q.pop();

        if(q.empty()) break;
         top = -q.top().first;
        id = q.top().second;


        //cout <<" top = "<<top <<"id = " << id<< endl;
        //cout <<"arr[i].l = " <<arr[i].l << endl;
    }
    }
    //cout << "use = " <<use << " q.size() = " << q.size() << endl;
    if(use-q.size()>0){
        for(int j = 1;j<=use;++j){
            if(!now[j]){
                now[j] = 1;
                ans[arr[i].id] = j;
                q.push(make_pair(-arr[i].r,arr[i].id));
                break;
            }
        }
    }
    else {
        use++;
        ans[arr[i].id] = use;
        q.push(make_pair(-arr[i].r,arr[i].id));
        now[use] = 1;
    }
    }
    printf("%d\n",use);
    for(int i = 1;i<=n;++i)
        printf("%d\n",ans[i]);
    }
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值