General Problem Solving Techniques [Intermediate-1]~D - Fabled Rooks

We would like to place n rooks, 1 ≤ n ≤ 5000, on a n × n
board subject to the following restrictions
• The i-th rook can only be placed within the rectangle
given by its left-upper corner (xli
, yli) and its rightlower
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 the same column or the same row.
Input
The input consists of several test cases. The first line of each
of them contains one integer number, n, the side of the board. n lines follow giving the rectangles
where the rooks can be placed as described above. The i-th line among them gives xli
, yli
, xri
, and
yri
. The input file is terminated with the integer ‘0’ on a line by itself.
Output
Your task is to find such a placing of rooks that the above conditions are satisfied and then output n
lines each giving the position of a rook in order in which their rectangles appeared in the input. If there
are multiple solutions, any one will do. Output ‘IMPOSSIBLE’ if there is no such placing of the rooks.
Sample Input
8
1 1 2 2
5 7 8 8
2 2 5 5
2 2 5 5
6 3 8 6
6 3 8 5
6 3 8 8
3 6 7 8
8
1 1 2 2
5 7 8 8
2 2 5 5
2 2 5 5
6 3 8 6
6 3 8 5
6 3 8 8
3 6 7 8
0
Sample Output
1 1
5 8
2 4
4 2
7 3
8 5
6 6
3 7
1 1
5 8
2 4
4 2
7 3
8 5
6 6
3 7

解题思路:题目意思是在n*n棋盘上放n辆车,是的任意两辆车不互相攻击,且第i辆车在一个给定的矩形Ri之内。题中最关键的一点是每辆车的x坐标和y坐标可以分开考虑(他们互不影响),可以先考虑将各辆车分布在同一列的不同行,然后再进行列分配。使得它们彼此错开。

程序代码:

#include"string.h"
#include"stdio.h"
#include"algorithm"
#include"iostream"
using namespace std;

const int N=5005;
int x1[N],x2[N],y1[N],y2[N],x[N],y[N];
int func(int *a,int *b,int *c,int n)
{
    fill(c,c+n,-1);
    for(int i=1;i<=n;i++)
    {
        int left=-1,right=n+1;
        for(int j=0;j<n;j++)
        {
            if(c[j]<0&&i>=a[j]&&b[j]<right)
            {
                left=j;
                right=b[j];
            }
        }
        if(left<0||i>right)
            return false;
        c[left]=i;
    }
    return true;
}
int main()
{
    int t;
    while(scanf("%d",&t)&&t)
    {
        for(int i=0;i<t;i++)
            scanf("%d%d%d%d",&x1[i],&y1[i],&x2[i],&y2[i]);
        if(func(x1,x2,x,t)&&func(y1,y2,y,t))
        {
            for(int i=0;i<t;i++)
                printf("%d %d\n",x[i],y[i]);
        }
        else
            printf("IMPOSSIBLE\n");
    }
    return 0;
}
posted @ 2015-10-09 14:44  简约。  阅读(230)  评论(0编辑  收藏  举报