111. 畜栏预定

原题链接:111. 畜栏预定


解题思路

按照开始吃草的时间把牛排序。

维护一个数组S,记录当前每个畜栏安排进去的最后一头牛,最初没有畜栏。

依次对每头牛,扫描数组S,找到任意一个畜栏,满足当前的牛开始吃草的时间不早于畜栏中最后一头牛结束吃草的时间。如果这样的畜栏不存在,则为其新建一个畜栏。

这个贪心算法的时间复杂度为 O(N2) 。我们可以利用一个小根堆维护每一个畜栏最后一头牛结束吃草的时间,尝试把当前的牛安排在堆顶(结束时间最早)的畜栏中,时间复杂度可以降到O(NlogN)

样例代码

#include<bits/stdc++.h>
using namespace std;
typedef pair<int,int> PII;
const int N = 50010;
int n;
int id[N];
pair<PII, int> cows[N];
int main()
{
    cin>>n;
    for(int i=0;i<n;i++)
    {
        cin>>cows[i].first.first>>cows[i].first.second;
        cows[i].second=i;
    }
    sort(cows,cows+n);
    priority_queue<PII, vector<PII>, greater<PII>> heap;
    for(int i=0;i<n;i++)
    {
        if(heap.empty()||heap.top().first>=cows[i].first.first)
        {
            PII stall={cows[i].first.second,heap.size()};
            id[cows[i].second]=stall.second;
            heap.push(stall);
        }
        else
        {
            auto stall=heap.top();
            heap.pop();
            stall.first=cows[i].first.second;
            id[cows[i].second]=stall.second;
            heap.push(stall);
        }
    }
    cout << heap.size() << endl;
    for (int i = 0; i < n; i ++ ) 
        cout << id[i] + 1 << endl;
    return 0;
}
原文地址:https://www.cnblogs.com/hnkjdx-ssf/p/14285444.html