poj3190Stall Reservations 贪心+堆优化

题目

Oh those picky N (1 <= N <= 50,000) cows! They are so picky that each one will only be milked over some precise time interval A..B (1 <= A <= B <= 1,000,000), which includes both times A and B. Obviously, FJ must create a reservation system to determine which stall each cow can be assigned for her milking time. Of course, no cow will share such a private moment with other cows.

Help FJ by determining:
The minimum number of stalls required in the barn so that each cow can have her private milking period
An assignment of cows to these stalls over time
Many answers are correct for each test dataset; a program will grade your answer.
有N头牛在畜栏中挤奶。每个畜栏在同一时间段只能提供给一头牛挤奶,所以可能会需要多个畜栏。给定N头牛和每头牛开始挤奶和结束挤奶的时间,每头牛在给定时间段内会一直挤奶(包括开始时刻和结束时刻),求需要的最小畜栏数目和每头牛对应的畜栏方案。
N<=50000

题解

贪心
按照开始吃草的时间把牛排序。
维护一个数组S,记录每个已有的畜栏最后一头牛的结束挤奶时间,对于每头未安排的牛,扫描数组S,找到任意一个畜栏(可以任意一个对答案无影响,因为下一头牛开始时间一定比该牛迟,所以把这个适合该牛的畜栏留给下一头牛没有什么用),满足该牛的开始时间大于畜栏中的结束时间。如果不存在,为该牛新建一个畜栏。
但是这样做时间复杂度是O(n^2),所以可以用一个小根堆维护每个畜栏最后一头牛结束吃草的时间,尝试吧当前牛安排在堆顶(结束时间最早)的畜栏中,此时复杂度为O(n lon n)

priority_queue

STL自带大根堆长这样:

#include <queue>

using namespace std;

priority_queue<int> q;//priority_queuq<变量类型> 堆的名字

int main(){
    q.push(n);//把变量n插入堆中,O(log n)
    int x=q.top();//查询堆顶元素,O(1)
    q.pop();//弹出堆顶元素,O(log n)
}

如果需要小根堆,有几种常见的方法:
1.当堆中存放的是单个变量时,可以取相反数放入堆,取出时再取相反数得到数据
2.priority_queue<int,vector<int>,greater<int> >q;
//注意“>q”前面的空格
3.自定义结构体,并重载小于号
这个超级烦烦烦烦烦烦烦烦烦烦烦烦烦烦烦!

#include<queue>

using namespace std;

struct smc{
    int m,c;
};
priority_queue<smc> q;

bool operator <(const smc &a,const smc &b){
    return a.m<b.m;
}//重载小于号!高级吧

int main(){
    smc x;
    x.m=1;
    x.c=2;
    q.push(x);
    smc d=q.top();
    q.pop();

代码

#include <cstdio>
#include <algorithm>
#include <queue> 

using namespace std;

int n,cnt;
struct node{ 
    int st,ed;
    int tr,y;
}a[50004];
struct smc{
    int m,c;
};
priority_queue<smc> q;  

bool comp(node a,node b){
    return a.st<b.st;
} 

bool operator <(const smc &a, const smc &b){
    return a.m>b.m;
}

bool mycf(node a,node b){
    return a.y<b.y;
}

int main(){
    scanf("%d",&n);
    for (int i=1;i<=n;i++,a[i].y=i)
        scanf("%d%d",&a[i].st,&a[i].ed);
    sort(a+1,a+n+1,comp);
    smc d;
    d.m=a[1].ed;
    d.c=++cnt;
    q.push(d);
    a[1].tr=1;
    for (int i=2;i<=n;i++){
        smc x=q.top();
        if (a[i].st<=x.m){
            smc e;
            e.m=a[i].ed;
            e.c=++cnt;
            q.push(e);
            a[i].tr=cnt;
        } else
        { 
            q.pop();
            x.m=a[i].ed;
            q.push(x);
            a[i].tr=x.c;
        }
    }
    sort(a+1,a+n+1,mycf);
    printf("%d\n",cnt); 
    for (int i=1;i<=n;i++)
        printf("%d\n",a[i].tr);
}

猜你喜欢

转载自blog.csdn.net/yjy_aii/article/details/81707105