Problem F: Fabled Rooks
We would like to place n rooks,1 ≤ n ≤ 5000, on a n×nboard subject to the following restrictions- Thei-th rook can only be placed within the rectangle given byits 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 thesame column or the same row.
The input consists of several test cases.The first line of each of them contains one integer number, n, theside of the board. n lines follow giving the rectangles wherethe rooks can be placed as described above. The i-th lineamong 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 conditionsare satisfied and then output n lines each giving the positionof a rook in order in which their rectangles appeared in the input. Ifthere are multiple solutions, any one will do. OutputIMPOSSIBLE 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 <algorithm>
#include <cstring>
#include <cmath>
#include <vector>
#include <queue>
#include <map>
#include <string>
using namespace std;
#define ff(i, n) for(int i=0;i<(n);i++)
#define fff(i, n, m) for(int i=(n);i<=(m);i++)
#define dff(i, n, m) for(int i=(n);i>=(m);i--)
#define mem(a) memset((a), 0, sizeof(a))
typedef long long LL;
typedef unsigned long long ULL;
void work();
int main()
{
#ifdef ACM
freopen("in.txt", "r", stdin);
// freopen("in.txt", "w", stdout);
#endif // ACM
work();
}
/*****************************************/
struct Node
{
int l, r, idx;
bool operator<(const Node & cmp) const
{
return r > cmp.r;
}
} x, y;
vector<Node> vx[5555], vy[5555];
int xx[5555], yy[5555];
int n;
bool gao(vector<Node> *v, int* arr)
{
priority_queue<Node> que;
fff(i, 1, n)
{
ff(j, v[i].size())
que.push(v[i][j]);
if(que.size() == 0)
return false;
x = que.top();
que.pop();
if(x.r < i)
return false;
arr[x.idx] = i;
}
return true;
}
void work()
{
while(~scanf("%d", &n) && n)
{
ff(i, 5555) vx[i].clear(), vy[i].clear();
ff(i, n)
{
scanf("%d%d%d%d", &x.l, &y.l, &x.r, &y.r);
x.idx = y.idx = i;
vx[x.l].push_back(x);
vy[y.l].push_back(y);
}
bool flag = true;
flag &= gao(vx, xx);
flag &= gao(vy, yy);
if(flag)
ff(i, n) printf("%d %d\n", xx[i], yy[i]);
else
puts("IMPOSSIBLE");
}
}