11134-Fabled Rooks【贪心 + 优先队列 + 思想转化】

来源:互联网 发布:ubuntu mate 安装pyqt 编辑:程序博客网 时间:2024/06/05 07:13

这题主要学习了一下贪心的方法,和优先队列priority_queue的使用

贪心策略就是 每次 左边界 小的 并且 右边界 小的出队列,其次需要根据位置不断更新左边边界值

#include<cstdio>#include<cstring>#include<algorithm>#include<map>#include<stack>#include<iostream>#include<queue>#include<set>#include<vector>#include<cmath>using namespace std;#define MAXD 5000 + 100struct Car{    int l,r;    int ID;    friend bool operator < (Car p,Car q){        if(p.l != q.l){            if(p.l > q.l) return true;            else            return false;        }        else {            if(p.r > q.r) return true;            else            return false;       }    }}car[MAXD];int n;int main(){    while(scanf("%d",&n) && n){        priority_queue<Car>q1;        priority_queue<Car>q2;        for(int i = 0 ; i < n ; i++){            Car temp1,temp2;            scanf("%d%d%d%d",&temp1.l,&temp2.l,&temp1.r,&temp2.r);            temp1.ID = i + 1;  temp2.ID = i + 1;            q1.push(temp1);            q2.push(temp2);        }        int now_pos = 1;        int ok = 1;        int _x[MAXD],_y[MAXD];        while(!q1.empty()){            Car t = q1.top();            q1.pop();            if(t.l < now_pos){                t.l = now_pos;                q1.push(t);            }            else if(t.l > now_pos || t.r < now_pos){                ok = 0;                break;            }            else{                _x[now_pos++] = t.ID;            }        }        now_pos = 1;        if(ok)while(!q2.empty()){            Car t = q2.top();            q2.pop();            if(t.l < now_pos){                t.l = now_pos;                q2.push(t);            }            else if(t.l > now_pos || t.r < now_pos){                ok = 0;                break;            }            else{                _y[now_pos++] = t.ID;            }        }        int ans_x[MAXD],ans_y[MAXD];        for(int i = 1 ; i <= n ; i++){            int t = _x[i];            ans_x[t] = i;            for(int j = 1 ; j <= n ; j++)if(_y[j] == t){                ans_y[t] = j;                break;            }        }        if(ok) for(int i = 1 ; i <= n ; i++)          printf("%d %d\n",ans_x[i],ans_y[i]);        else          printf("IMPOSSIBLE\n");    }    return 0;}

 

0 0
原创粉丝点击