Problem F: 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 (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
行和列是无关了,所以分别贪心行和列,把区间排序,然后从左往右找,已经被用过的位置不能再用,注意找到区间右端点外面后可以标记失败退出了。
AC代码:
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cctype>
#include <cstring>
#include <string>
#include <sstream>
#include <vector>
#include <set>
#include <map>
#include <algorithm>
#include <stack>
#include <queue>
#include <bitset>
#include <cassert>
#include <cmath>
using namespace std;
const int maxn = 5005;
struct Edge
{
int l, r, id;
}edgeX[maxn], edgeY[maxn];
int ansX[maxn], ansY[maxn];
set<int> setX, setY;
bool camp(Edge a, Edge b)
{
return a.r < b.r;
}
int main()
{
ios::sync_with_stdio(false);
int n;
int xl, yl, xr, yr;
while (cin >> n && n) {
setX.clear();
setY.clear();
for (int i = 1; i <= n; i++) {
cin >> xl >> yl >> xr >> yr;
edgeX[i].l = xl;
edgeX[i].r = xr;
edgeY[i].l = yl;
edgeY[i].r = yr;
edgeX[i].id = edgeY[i].id = i;
setX.insert(i);
setY.insert(i);
}
setX.insert(10000000);
setY.insert(10000000);
// 把区间按照又边界排序
sort(edgeX + 1, edgeX + n + 1, camp);
sort(edgeY + 1, edgeY + n + 1, camp);
bool flag = false;
for (int i = 1; i <= n && !flag; i++) {
int tmpX = *setX.lower_bound(edgeX[i].l);
if (tmpX > edgeX[i].r) { // 越界,标记退出
flag = true;
}
ansX[edgeX[i].id] = tmpX;
setX.erase(tmpX);
int tmpY = *setY.lower_bound(edgeY[i].l);
if (tmpY > edgeY[i].r) { // 越界,标记退出
flag = true;
}
ansY[edgeY[i].id] = tmpY;
setY.erase(tmpY);
}
if (flag) {
cout << "IMPOSSIBLE\n";
continue;
}
for (int i = 1; i <= n; i++) {
cout << ansX[i] << " " << ansY[i] << endl;
}
}
return 0;
}