POJ31900(贪心)

16 篇文章 0 订阅

想对了一半,还是不扎实

  1. 原本想将初始化和之后处理一起放到for里面的(i.e. 将push, ans = 1等放到for里面),发现比较麻烦,然后死磕这个,要建函数什么的,看了人家的代码之后发现没有必要,当然是美观了一点。其实能不能将初始化和处理一起写最重要的是看你的思路 is clear or not, sometimes it can unified. But in this case, it need something in the queue, otherwise we need to check every time.

  2. Know how to compare with struct, it has different flavors, I think the compares below is clear for use.

  3. Why there is no different when pop the earliest element then push a current element between find the nearest element to modify?
    Because the cows are sorted by starting time, which means the cow you currently maintains is the earliest one. And our greedy algorithm is earlier appear earlier to use.
//#define LOCAL

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
#define N 50010

using namespace std;

struct interval{
    int begin;
    int end;
    int num;

    friend bool operator <(interval a, interval b){
        if(a.end == b.end)
            return a.begin < b.begin;

        return a.end > b.end;
    }
}a[N];

bool cmp(interval a, interval b){
    if(a.begin == b.begin)
        return a.end < b.end;

    return a.begin < b.begin;   
}

int main(void){
#ifdef LOCAL
    freopen("data.in", "r", stdin);
#endif

    int n;
    int order[N]; 
    priority_queue<interval> q;

    scanf("%d", &n);
    for(int i = 0; i < n; i++){
        scanf("%d%d", &a[i].begin, &a[i].end);
        a[i].num = i;
    }
    sort(a, a + n, cmp);

#ifdef LOCAL
    for(int i = 0; i < n; i++)
        printf("begin:%d end:%d num:%d\n", 
            a[i].begin, a[i].end, a[i].num);
#endif

    int ans = 1;
    q.push(a[0]);
    order[a[0].num] = ans;

    for(int i = 1; i < n; i++){
        interval temp = q.top();

#ifdef LOCAL
        printf("begin:%d end:%d num:%d\n", 
            temp.begin, temp.end, temp.num);
#endif

        if(temp.end < a[i].begin){
            order[a[i].num] = order[temp.num];
            q.pop();
        }else{
            ans++;
            order[a[i].num] = ans;
        }
        q.push(a[i]);
    }

    printf("%d\n", ans);
    for(int i = 0; i < n; i++)
        printf("%d\n", order[i]);

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值