11134 - Fabled Rooks
We would like to place
n
rooks,
• 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 <script type="math/tex" id="MathJax-Element-277">n</script> 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
题意
类似八皇后问题,区别是没有了斜45度方向的限制,数据范围是5000,并且每个棋子只会出现在给定的矩形区域。
题解
可以看出行和列的分布是互不影响的,问题可分解为两个一维空间的分布问题。贪心的过程是从区间的一个端点开始贪心,比如现在要找x的分布,那么从第一列开始贪心,找到所有可以放在第一列的棋子中r值最小的,因为r值小,所以这个棋子可以选择的位置更少,如果换成一个r值更大的棋子结果不会更优。(代码写得比较丑。。跑了600ms)
代码
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <algorithm>
#include <queue>
#include <vector>
#include <map>
#define fout freopen("out.txt","w",stdout)
#define fin freopen("in.txt","r",stdin)
using namespace std;
int n;
int now;
int mark;
struct node
{
int l,r,id;
bool operator<(const node &R)const
{
if(l<=now&&R.l<=now)
return r<R.r;
return l<=now;
}
};
node A[5005],B[5005];
int x[5005],y[5005];
int main()
{
while(scanf("%d",&n)&&n!=0)
{
mark=1;
for(int i=1;i<=n;i++)
{
A[i].id=B[i].id=i;
scanf("%d%d%d%d",&A[i].l,&B[i].l,&A[i].r,&B[i].r);
}
for(now=1;now<=n;now++)
{
sort(A+now,A+n+1);
sort(B+now,B+n+1);
if(A[now].l>now||A[now].r<now||B[now].l>now||B[now].r<now)
{
printf("IMPOSSIBLE\n");
mark=0;
break;
}
x[A[now].id]=now;
y[B[now].id]=now;
}
if(mark)
{
for(int i=1;i<=n;i++)
printf("%d %d\n",x[i],y[i]);
}
}
return 0;
}