Problem UVA11134-Fabled Rooks
Accept: 716 Submit: 6134
Time Limit: 3000mSec
Problem Description
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 (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
Sample Input
#include <bits/stdc++.h> using namespace std; const int maxn = + ; int n; struct Interval {
pair<int, int> interval;
int pos;
}hor[maxn], ver[maxn]; bool cmp(const Interval &a, const Interval &b) {
if (a.interval.second == b.interval.second) return a.interval.first > b.interval.first;
else return a.interval.second < b.interval.second;
} bool hvis[maxn], vvis[maxn];
int vans[maxn], hans[maxn]; int main()
{
//freopen("input.txt", "r", stdin);
while (~scanf("%d", &n) && n) {
memset(hvis, false, sizeof(hvis));
memset(vvis, false, sizeof(vvis));
int xl, yl, xr, yr;
for (int i = ; i <= n; i++) {
scanf("%d%d%d%d", &xl, &yl, &xr, &yr);
ver[i].interval = make_pair(xl, xr);
ver[i].pos = i;
hor[i].interval = make_pair(yl, yr);
hor[i].pos = i;
} sort(ver + , ver + + n, cmp);
sort(hor + , hor + + n, cmp); bool ok = true; for (int i = ; i <= n; i++) {
int l = ver[i].interval.first, r = ver[i].interval.second;
int p = ver[i].pos;
int j;
for (j = l; j <= r; j++) {
if (!vvis[j]) {
vvis[j] = true;
vans[p] = j;
break;
}
}
if (j == r + ) { ok = false; break; }
} if (!ok) {
printf("IMPOSSIBLE\n");
continue;
} for (int i = ; i <= n; i++) {
int l = hor[i].interval.first, r = hor[i].interval.second;
int p = hor[i].pos;
int j;
for (j = l; j <= r; j++) {
if (!hvis[j]) {
hvis[j] = true;
hans[p] = j;
break;
}
}
if (j == r + ) { ok = false; break; }
} if (!ok) {
printf("IMPOSSIBLE\n");
continue;
} for (int i = ; i <= n; i++) {
printf("%d %d\n", vans[i], hans[i]);
}
}
return ;
}