UVa 11134 Fabled Rooks 解题报告(贪心)

来源:互联网 发布:富甲天下3武将数据 编辑:程序博客网 时间:2024/06/03 10:01

Problem F: Fabled Rooks

We would like to placen rooks,1 ≤ n ≤ 5000, on a n×nboard subject to the following restrictions
  • Thei-th rook can only be placed within the rectangle given byits left-upper corner (xli,yli) and its right-lower corner(xri,yri), where 1 ≤ i ≤ n,1 ≤ xli ≤ xri ≤ n,1 ≤ yli ≤ yri ≤ n.
  • No two rooks can attack each other, that is no two rooks can occupy thesame column or the same row.

The input consists of several test cases.The first line of each of them contains one integer number,n, theside of the board. n lines follow giving the rectangles wherethe rooks can be placed as described above. Thei-th lineamong them gives xli, yli,xri, andyri. The input file is terminated with the integer `0' on a line by itself.

Your task is to find such a placing of rooks that the above conditionsare satisfied and then outputn lines each giving the positionof a rook in order in which their rectangles appeared in the input. Ifthere are multiple solutions, any one will do. OutputIMPOSSIBLE if there is no such placing of the rooks.

Sample input

81 1 2 25 7 8 82 2 5 52 2 5 56 3 8 66 3 8 56 3 8 83 6 7 881 1 2 25 7 8 82 2 5 52 2 5 56 3 8 66 3 8 56 3 8 83 6 7 80

Output for sample input

1 15 82 44 27 38 56 63 71 15 82 44 27 38 56 63 7


    解题报告: 很好的题目。仔细看会发现行和列其实是分开的,我们可以分别来求。然后单独看行,按照离谁的右边界最近,优先分配给谁的原则。类似于处理器处理任务那题。这样来看就很简单了。代码如下:

#include <iostream>#include <cstdio>#include <algorithm>#include <cstring>#include <cmath>#include <vector>#include <queue>#include <map>#include <string>using namespace std;#define ff(i, n) for(int i=0;i<(n);i++)#define fff(i, n, m) for(int i=(n);i<=(m);i++)#define dff(i, n, m) for(int i=(n);i>=(m);i--)#define mem(a) memset((a), 0, sizeof(a))typedef long long LL;typedef unsigned long long ULL;void work();int main(){#ifdef ACM    freopen("in.txt", "r", stdin);//    freopen("in.txt", "w", stdout);#endif // ACM    work();}/*****************************************/struct Node{    int l, r, idx;    bool operator<(const Node & cmp) const    {        return r > cmp.r;    }} x, y;vector<Node> vx[5555], vy[5555];int xx[5555], yy[5555];int n;bool gao(vector<Node> *v, int* arr){    priority_queue<Node> que;    fff(i, 1, n)    {        ff(j, v[i].size())            que.push(v[i][j]);        if(que.size() == 0)            return false;        x = que.top();        que.pop();        if(x.r < i)            return false;        arr[x.idx] = i;    }    return true;}void work(){    while(~scanf("%d", &n) && n)    {        ff(i, 5555) vx[i].clear(), vy[i].clear();        ff(i, n)        {            scanf("%d%d%d%d", &x.l, &y.l, &x.r, &y.r);            x.idx = y.idx = i;            vx[x.l].push_back(x);            vy[y.l].push_back(y);        }        bool flag = true;        flag &= gao(vx, xx);        flag &= gao(vy, yy);        if(flag)            ff(i, n) printf("%d %d\n", xx[i], yy[i]);        else            puts("IMPOSSIBLE");    }}


0 0