L - Fabled Rooks(中途相遇法和贪心)

时间:2024-07-17 17:07:32

Problem F: Fabled Rooks

L - 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 (xliyli) and its right-lower corner (xriyri), 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 xliylixri, 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 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 <cstdio>
#include <cstring>
//#include <cmath> 命名冲突 y1
#include <algorithm>
#include <string>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <list>
#include <iomanip>
#include <cstdlib>
#include <sstream>
using namespace std;
typedef long long LL;
const int INF=0x5fffffff;
const double EXP=1e-;
const int MS=; int x1[MS], y1[MS], x2[MS], y2[MS], x[MS], y[MS]; /*
先将各个车分配在同一列的不同行,然后分配不同的列,
使他们彼此错开,任意两个车不在同一列和同一行。
也就是说行和列的分配时可以分开的。或者说独立的
使用贪心法分配。
*/ bool solve(int *a,int *b,int *c,int n)
{
// memset(c,-1,sizeof(c)); 注意这样是错误的,因为不知道c到哪里结束。字符串指针才可以,因为有结束符
fill(c,c+n,-); // ==-1表示还没有分配
for(int col=;col<=n;col++)
{
int rook=-,minb=n+;
for(int i=;i<n;i++)
{
if(c[i]<&&col>=a[i]&&b[i]<minb)
{
rook=i;
minb=b[i];
}
}
if(rook<||col>minb)
return false;
c[rook]=col;
}
return true;
} int main()
{
int n;
while(scanf("%d",&n)&&n)
{
for(int i=;i<n;i++)
scanf("%d%d%d%d",&x1[i],&y1[i],&x2[i],&y2[i]);
if(solve(x1,x2,x,n)&&solve(y1,y2,y,n))
for(int i=;i<n;i++)
printf("%d %d\n",x[i],y[i]);
else
printf("IMPOSSIBLE\n");
}
return ;
}