We would like to place n rooks,  ≤ n ≤ , 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 ≤ i ≤ n, ≤ xli ≤xri ≤ n, ≤ 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, andyri.
The input file is terminated with the integer ‘’ 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

Sample Output

解题思路:

  经过分析可以发现,每个车横纵坐标的选取是相互独立的,因此可以分别考虑。那么问题可以简化成:将1~n 分别放入[xli,xri]n个区间中。选择的方法采用贪心法——以行为例,先将各个矩形区间按 xr 从小到大排序 [xl1,xr1][xl2,xr2]...[xln,xrn];依次选择每个区间中尽量靠xl的未放置车的位置,比如针对[xl1,xr1],应将车放入xl1位置,此时对于区间[xl2,xr2],xl1位置不再考虑。

代码如下:

 #include <iostream>
#include <cstdio>
#include <cstring>
#include <ctime>
#include <algorithm>
using namespace std;
#define time__ printf("time: %f\n",double(clock())/CLOCKS_PER_SEC)
const int maxn=;
struct Rec{
int xl,yl,xr,yr;
};
Rec rect[maxn+];
int id[maxn+];
int id_row_num[maxn+];
int id_col_num[maxn+];
int row[maxn+];
int col[maxn+];
int n;
void init(){
memset(id_row_num, , sizeof id_row_num);
memset(id_col_num, , sizeof id_col_num);
memset(row, , sizeof row);
memset(col,,sizeof col);
}
bool cmp_row(int &a,int &b){
return rect[a].xr<rect[b].xr;
}
bool cmp_col(int &a,int &b){
return rect[a].yr<rect[b].yr;
}
bool solve_row(){
for(int i=;i<=n;i++)
id[i]=i;
sort(id+, id++n, cmp_row);
//bool ok=true;
for(int i=;i<=n;i++){
Rec &t=rect[id[i]];
bool flag=false;
for(int j=t.xl;j<=t.xr;j++){
if(row[j]==){
row[j]=;
id_row_num[id[i]]=j;
flag=true;
break;
}
}
if(!flag){
return false;
}
}
return true;
}
bool solve_col(){
for(int i=;i<=n;i++)
id[i]=i;
sort(id+, id++n, cmp_col);
//bool ok=true;
for(int i=;i<=n;i++){
Rec &t=rect[id[i]];
bool flag=false;
for(int j=t.yl;j<=t.yr;j++){
if(col[j]==){
col[j]=;
id_col_num[id[i]]=j;
flag=true;
break;
}
}
if(!flag){
return false;
}
}
return true;
} int main(int argc, const char * argv[]) {
while(scanf("%d",&n)==&&n){
init();
for(int i=;i<=n;i++)
scanf("%d%d%d%d",&rect[i].xl,&rect[i].yl,&rect[i].xr,&rect[i].yr);
if(solve_row()&&solve_col()){
for(int i=;i<=n;i++)
printf("%d %d\n",id_row_num[i],id_col_num[i]);
}
else printf("IMPOSSIBLE\n");
//time__;
}
//time__;
return ;
}
05-11 04:30