Problem F: Fabled Rooks
![](http://uva.onlinejudge.org/external/111/p11134.jpg)
- The i-th rook can only be placed within the rectangle given by its 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 the same column or the same row.
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.
Your task is to find such a placing of rooks that the above conditions are satisfied and then outputn 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
Output for sample input
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
#include<iostream>
#include<algorithm>
#define M 5005
using namespace std;
int fun(int *x,int *y,int *xy,int n)
{
fill(xy,xy+n,-1);//将xy数组全置为-1
int i,j;
for(i=1;i<=n;i++)
{
int r=-1,min=n+1;
for(j=0;j<n;j++)
//判断边界,找出下边接最小的那个
if(xy[j]<0&&y[j]<min&&i>=x[j]) {r=j;min=y[j];}
if(r<0||i>min) return 0;//越界或者没有这个区间
xy[r]=i;
}
return 1;
}
int main()
{
int x1[M],y1[M],x2[M],y2[M],x[M],y[M],i,n;
while(cin>>n)
{
if(n==0) break;
for(i=0;i<n;i++)
cin>>x1[i]>>y1[i]>>x2[i]>>y2[i];
if(fun(x1,x2,x,n)&&fun(y1,y2,y,n))
for(i=0;i<n;i++)
cout<<x[i]<<" "<<y[i]<<endl;
else
cout<<"IMPOSSIBLE"<<endl;
}
return 0;
}