题目链接:点击打开链接
题目大意:传统题目变形。在n*n的棋盘上放置n个车,使得他们不会互相攻击,而且没个车的范围限制在一个矩形内,矩形的左上角,右下角坐标被给出。对于每个样例,如果能够在限制条件下摆出所有车,输出所有车的坐标。否则输出IMPOSSIBLE。
思路:贪心 优先队列
分析:
1. 车摆放的横坐标和纵坐标是互相独立的,也就是说我们可以先为每个车分配x坐标,接着再分配y坐标。这样问题就转化成给定一系列范围,在一个数轴的每个区间上摆放一个车且不冲突。
2. 拿分配x坐标为例,从1-n依次分配,每次分配给xr尽量小的那个棋子。因为如果该棋子先分配都无法满足的话(x坐标超出xr),到后面x坐标增大,更无法满足该棋子了。我用优先队列来存放棋子。
代码:
#include <cstdio>
#include <queue>
#include <memory.h>
using namespace std;
const int maxn = 5000 + 5;
int position[maxn][2];
int n;
struct area
{
int l, r, order;
bool operator <(const area& a) const
{
if (l != a.l) return l > a.l;
return r > a.r;
}
} areax[maxn], areay[maxn];
void init()
{
for (int i = 0; i < n; ++i) {
scanf("%d %d %d %d", &areax[i].l, &areay[i].l, &areax[i].r, &areay[i].r);
areax[i].order = i;
areay[i].order = i;
}
}
bool check(area areas[maxn], int is_col)
{
priority_queue<area> a;
for (int i = 0; i < n; ++i)
a.push(areas[i]);
int number = 1;
while (!a.empty())
{
area top = a.top();
a.pop();
if (top.l > number || top.r < number) return false;
if (top.l < number)
{
top.l = number;
a.push(top);
continue;
}
position[top.order][is_col] = number;
++number;
}
return true;
}
void output()
{
for (int i = 0; i < n; ++i)
printf("%d %d\n", position[i][0], position[i][1]);
}
int main()
{
while (scanf("%d", &n) && n != 0)
{
init();
if (check(areax, 0) && check(areay, 1))
output();
else
printf("IMPOSSIBLE\n");
}
return 0;
}