UVA11134-Fabled Rooks(贪心)

题目链接

http://acm.hust.edu.cn/vjudge/problem/34086

题意

给定一个n x n的棋盘,在棋盘上摆放n个皇后,使其不相互攻击,并且对于每个皇后,给定一个矩阵区域,该皇后只能在这个矩形区域内,输出一个合法方案/impossible

思路

对于每个皇后,其摆放的x,y坐标是独立的,于是就将题意转化成了两个一维的问题:对于一个皇后,给定区间[l, r],只能在该区间上选择一点。最终使1-n中的所有点均能被选择。
于是题目转化成了一个经典的贪心问题,类似于活动安排问题:
首先将区间按照右端点从早到晚排序,右端点相同的,按左端点从早到晚排序。然后用位置去覆盖每个点

代码

#include <iostream>
#include <cstring>
#include <stack>
#include <vector>
#include <set>
#include <map>
#include <cmath>
#include <queue>
#include <sstream>
#include <iomanip>
#include <fstream>
#include <cstdio>
#include <cstdlib>
#include <climits>
#include <deque>
#include <bitset>
#include <algorithm>
using namespace std;

#define PI acos(-1.0)
#define LL long long
#define PII pair<int, int>
#define PLL pair<LL, LL>
#define mp make_pair
#define IN freopen("in.txt", "r", stdin)
#define OUT freopen("out.txt", "wb", stdout)
#define scan(x) scanf("%d", &x)
#define scan2(x, y) scanf("%d%d", &x, &y)
#define scan3(x, y, z) scanf("%d%d%d", &x, &y, &z)
#define sqr(x) (x) * (x)
#define pr(x) cout << #x << " = " << x << endl
#define lc o << 1
#define rc o << 1 | 1
#define pl() cout << endl
#define CLR(a, x) memset(a, x, sizeof(a))
#define FILL(a, n, x) for (int i = 0; i < n; i++) a[i] = x

const int maxn = 5005;
int dx[maxn], dy[maxn], n;

struct node {
    int l, r, id;
    node(int a, int b, int c) : l(a), r(b), id(c) {

    }
    node() {

    }
} L[maxn], R[maxn];

bool cmp(node x, node y) {
    if (x.r != y.r) return x.r < y.r;
    return x.l < y.l;
}

bool solve(node a[], int sta) {
    int vis[maxn], pos = 1;
    CLR(vis, 0);
    for (int i = 0; i < n; i++) {
        node &no = a[i];
        for (int j = no.l; j <= no.r; j++) {
            if (vis[j]) {
                if (j == no.r) return false;
                continue;
            }   
            vis[j] = 1;
            if (sta == 1) dx[no.id] = j;
            if (sta == 2) dy[no.id] = j;
            break;
        }
    }
    return true;
}

int main() {
    int x, y, z, w;
    while (scan(n) && n) {
        for (int i = 0; i < n; i++) {
            scanf("%d%d%d%d", &x, &y, &z, &w);
            L[i] = node(x, z, i);
            R[i] = node(y, w, i);
        }
        sort(L, L + n, cmp);
        sort(R, R + n, cmp);
        bool f1 = solve(L, 1);
        bool f2 = solve(R, 2);
        if (!f1 || !f2) 
            puts("IMPOSSIBLE");
        else 
            for (int i = 0; i < n; i++) cout << dx[i] << ' ' << dy[i] << endl;
    }
    return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值