POJ3190

来源:互联网 发布:酷派手机怎么设置网络 编辑:程序博客网 时间:2024/06/06 23:58

Problem: Stall Reservations
Description: 奶牛挤奶用机器的问题,一台机器同一时间只能为一头奶牛挤奶,问你最少需要多少台机器,然后再输出每头奶牛用了哪一台机器。
Solution: 贪心+排序+优先队列,我们开一个优先队列,意思就是队列中的奶牛正在使用机器挤奶。我们比较队头元素和我们排好序的奶牛开始时间,如果排好序的奶牛开始时间早于队头元素结束时间,那么我们就要用一台新机器来挤奶,否则,就可以用队头的机器来服务当前奶牛。
Code(C++):

#include <stdio.h>#include <string.h>#include <stdlib.h>#include <queue>using namespace std;const int M=50005;typedef struct tagTime{    int src,des;    int menchine;    int pos;    tagTime(){}    tagTime(int _src,int _des,int _menchine=0):        src(_src),des(_des),menchine(_menchine){}    bool operator<(const tagTime &other)const{        if(des!=other.des)            return des>other.des;        return src>other.src;    }}Time;int n;Time times[M];int ans[M];int top;int cmp(const void *a,const void *b){    Time *A=(Time *)a;    Time *B=(Time *)b;    if(A->src!=B->src)        return A->src-B->src;    if(A->des!=B->des)        return A->des-B->des;    return A->pos-B->pos;}int main(){    while(~scanf("%d",&n)){        // init        for(int i=0;i<n;i++)            scanf("%d%d",&times[i].src,&times[i].des),            times[i].pos=i;        qsort(times,n,sizeof(times[0]),cmp);        priority_queue<Time> que;        int cnt=1;        for(int i=0;i<n;i++)            if(que.empty()||que.top().des>=times[i].src)                que.push(Time(times[i].src,times[i].des,cnt)),                ans[times[i].pos]=cnt++;            else{                int tmp=que.top().menchine;                que.pop();                que.push(Time(times[i].src,times[i].des,tmp)),                ans[times[i].pos]=tmp;            }        printf("%d\n",cnt-1);        for(int i=0;i<n;i++)            printf("%d\n",ans[i]);    }    return 0;}
1 0