111. Corral Reservation【Greedy】

insert image description here

The classic greedy problem is very similar to the grouping problem. But here we have to maintain the coordinate information.

#include<bits/stdc++.h>
using namespace std;
#define x first
#define y second;
const int N=1e5+10;
typedef pair<int,int> PII;
struct node{
    
    int l,r,id;};
bool cmp(node a,node b)
{
    
    
    if(a.l!=a.l) return a.r<b.r;
    return a.l<b.l;
}
vector<node>ve;
int n,ans[N];
int main(void)
{
    
    
    cin>>n;
    for(int i=1;i<=n;i++)
    {
    
    
        int l,r; cin>>l>>r;
        ve.push_back({
    
    l,r,i});
    }
    sort(ve.begin(),ve.end(),cmp);
    priority_queue<PII,vector<PII>,greater<PII> >q;//小根堆 存每组最后一个数
    for(int i=0;i<n;i++)
    {
    
    
        int l=ve[i].l,r=ve[i].r;
        if(!q.size()) q.push({
    
    r,q.size()+1}),ans[ve[i].id]=q.size();
        else
        {
    
    
            auto temp=q.top();
            int x=temp.x,id=temp.y;
            if(x<l) 
            {
    
    
                q.pop();
                q.push({
    
    r,id});
                ans[ve[i].id]=id;
            }else
            {
    
    
                q.push({
    
    r,q.size()+1});
                ans[ve[i].id]=q.size();
            }
        }
    }
    cout<<q.size()<<endl;
    for(int i=1;i<=n;i++) cout<<ans[i]<<endl;
    return 0;
}

Guess you like

Origin blog.csdn.net/qq_46527915/article/details/123606724
111
Recommended