Problem F: Fabled Rooks
We would like to place- 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,
Your task is to find such a placing of rooks that the above conditions are satisfied and then outputn
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
题意: n*n的棋盘中, 有n个每个车给出它放置的范围, 并且使得每辆车不能相互攻击(不同行不同列).
如果可以做到输出全部车的位置.(输出一种结果即可)
解题思路:
1. 显然, 如果问题有解, 每个车都必须分配到一个(x,y), 并且x,y是相互独立的. 这里可以采取
贪心法, 枚举第i行(列)时, 如果有多个车可以放置, 我们选取最靠上(左)的一个放置, 这样
选择会使得不会让结果变得更差, 因为这样至少不会妨碍下一个范围的车选择放置位置.
2. 这里依然采用线段树来维护查找最靠上(左)的位置.
代码:
#include <cstdio>
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
#define MAX 5005
const int INF = (1<<29);
struct node
{
int x1, y1;
int x2, y2;
}a[MAX];
int n, D;
int pt[MAX*4], di[MAX*2];
int x[MAX], y[MAX];
inline void swap(int &a, int &b)
{
int temp = a;
a = b;
b = temp;
}
inline int getXY(int id)
{
return id > 0 ? a[id].x1 : a[-id].x2+1;
}
bool cmp(const int x, const int y)
{
int tx = getXY(x);
int ty = getXY(y);
return tx < ty;
}
inline void update(int i)
{
while(i^1)
{
pt[i>>1] = a[ pt[i] ].x2 < a[ pt[i^1] ].x2 ? pt[i] : pt[i^1];
i >>= 1;
}
}
void solve(int *x)
{
sort(di, di+2*n, cmp);
int cur = 0;
for(int i = 1; i <= n+1; ++i)
{
while(cur < 2*n) //全部可以放在i行(列)添加入线段树
{
int id = di[cur];
if(getXY(id) != i) break;
if(id > 0)
{
pt[D+id] = id;
update(D+id);
}
else
{
pt[D-id] = 0; //超出范围了, 从线段树中删除
update(D-id);
}
cur++;
}
int id = pt[1]; //贪心法, 选择出最小的一个
if(id == 0) continue;
x[id] = i;
pt[D+id] = 0; //已经选择了, 也从线段树中删除
update(D+id);
}
}
int main()
{
//freopen("input.txt", "r", stdin);
while(scanf("%d", &n) != EOF)
{
if(n == 0) break;
for(int i = 1; i <= n; ++i)
{
scanf("%d %d %d %d", &a[i].x1, &a[i].y1, &a[i].x2, &a[i].y2);
di[2*i-2] = i;
di[2*i-1] = -i;
}
for(D = 1; D < n+2; D <<= 1);
memset(pt, 0, sizeof(pt[0])*(2*D));
a[0].x2 = INF; //设置一个线段树删除标记
memset(x, 0, sizeof(x[0])*(n+1));
memset(y, 0, sizeof(y[0])*(n+1));
solve(x);
for(int i = 1; i <= n; ++i)
{
swap(a[i].x1, a[i].y1);
swap(a[i].x2, a[i].y2);
}
solve(y);
bool flag = false;
for(int i = 1; i <= n; ++i)
{
if(x[i] == 0 || y[i] == 0)
{
printf("IMPOSSIBLE\n");
flag = true;
break;
}
}
if( !flag )
{
for(int i = 1; i <= n; ++i)
printf("%d %d\n", x[i], y[i]);
}
}
return 0;
}