[Ybtoj high-efficiency advanced 1.2] [greedy] Corral reservation

[Ybtoj high-efficiency advanced 1.2] [greedy] Corral reservation

topic

Insert picture description here
Insert picture description here


Problem-solving ideas

Sort the time when the cows graze
and find out if there is a fence available
(that is, whether the last cow here has eaten up) The
best one must be the earliest end,
so you can use a small root pile to maintain the time when the last cow has eaten the grass.


Code

#include<algorithm>
#include<iostream>
#include<cstdio>
#include<queue>
using namespace std;
struct lzf{
    
    
	int l,r,id;
}a[50010];
struct yty{
    
    
	int r,id;
	bool operator < (const yty a) const
	{
    
    
		return a.r<r;
	}
};
int n,ans[50020];
bool cmp(lzf l,lzf y)
{
    
    
	 return l.l<y.l;
}
int main()
{
    
    
	priority_queue<yty> q;
	scanf("%d",&n);
	for (int i=1;i<=n;i++)
	{
    
    
	    a[i].id=i;
	    scanf("%d%d",&a[i].l,&a[i].r);
	}
	sort(a+1,a+n+1,cmp);
	for (int i=1;i<=n;i++)
	    if (!q.size()||q.top().r>=a[i].l)
	    {
    
    
	       ans[a[i].id]=q.size()+1;  //新建一个栅栏
	       q.push((yty){
    
    a[i].r,ans[a[i].id]});   //放入小根堆
		}
		else {
    
    
			ans[a[i].id]=q.top().id;  //取这个栅栏的编号
			q.pop();  //上一头牛退堆
			q.push((yty){
    
    a[i].r,ans[a[i].id]});  //放入小根堆
		}
    printf("%d\n",q.size());
    for (int i=1;i<=n;i++)
        printf("%d\n",ans[i]);
    return 0;
} 

Guess you like

Origin blog.csdn.net/qq_45621109/article/details/111714946