UVA 11134 - Fabled Rooks(贪心+优先队列)

解决在n×n棋盘上放置n辆车的问题,确保每辆车处于特定范围内且不互相攻击。采用贪心算法结合优先队列的方法进行求解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

We would like to placenrooks, 1≤n≤5000, on an×nboard subject to the following restrictions
  • Thei-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≤in, 1≤xlixrin, 1≤yliyrin.
  • 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.nlines follow giving the rectangles where the rooks can be placed as described above. Thei-th line among them givesxli,yli,xri, andyri. 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 outputnlines 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. OutputIMPOSSIBLEif 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
题意:给定n辆车可以放在棋盘的区间,求能否放满且所有车不受攻击。
思路:贪心+优先队列,把行列分开去贪心。。
代码:
#include <stdio.h>
#include <string.h>
#include <queue>
#include <algorithm>
using namespace std;

const int N = 5005;

int n;
struct Car {
    int xl, xr, yl, yr;
    int px, py, id;
} car[N];

bool cmp1(Car a, Car b) {
    if (a.yl != b.yl)
	return a.yl < b.yl;
    return a.yr < b.yr;
}

bool cmp2(Car a, Car b) {
    if (a.xl != b.xl)
	return a.xl < b.xl;
    return a.xr < b.xr;
}

bool cmp3(Car a, Car b) {
    return a.id < b.id;
}

void init() {
    for (int i = 0; i < n; i ++) {
	scanf("%d%d%d%d", &car[i].xl, &car[i].yl, &car[i].xr, &car[i].yr);
	car[i].id = i;
    }
}

bool solve() {
    sort(car, car + n, cmp1);
    for (int i = 1; i <= n; i ++) {
	if (car[i - 1].yl > i || car[i - 1].yr < i) return false;
	car[i - 1].py = i;
    }
    sort(car, car + n, cmp2);
    for (int i = 1; i <= n; i ++) {
	if (car[i - 1].xl > i || car[i - 1].xr < i) return false;
	car[i - 1].px = i;
    }
    sort(car, car + n, cmp3);
    return true;
}

int main() {
    while (~scanf("%d", &n) && n) {
	init();
	if (solve()) {
	    for (int i = 0; i < n; i ++)
		printf("%d %d\n", car[i].px, car[i].py);
	}
	else printf("IMPOSSIBLE\n");
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值