uva 11134 - Fabled Rooks 优先队列 + 贪心

题目大意:给定n个矩形区间,问如何才能够使得在一个n*n的棋盘上,任意两个车不在同一行也不再同一列。

数据范围为:0<n <= 5000 . 

解题:此题必须得注意到x和y是可以分开的,只需要一个id来标识就可以了。可以这样思考:计算x的时候确定行数,计算y的时候确定了列数。计算x和y分别保证了行不会相同,列不会相同。接下来就是区间选点问题了。这个与刘汝佳先生在算法竞赛入门经典中的区间选点问题一样都是选择贪心算法只不过这里选择的是区间的考前的点。

我们按照 区间的最左点  l从下到大排序,如果不重合,则区间内的任一点都可以选择,如果重合的话我们选择区间的最左可能点,因为这样肯定不会妨碍后面的区间选点。这里我们可以使用优先队列来实现每次的区间选择问题。



//
//  main.cpp
//  uva 11134 - Fabled Rooks
//
//  Created by XD on 15/8/13.
//  Copyright (c) 2015年 XD. All rights reserved.
//

#include <iostream>
#include <string>
#include <queue>
#include <stack>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include<vector>
#include <string.h>
#include <string>
#include <algorithm>
#include <set>
#include <map>
#include <cstdio>
using namespace std ;
int n ;
struct node {
    int l, r ,id;
    bool operator < (const node     &n ) const{
//        return  cost < n.cost ;
        if(l==n.l) return r > n.r ;
        else return l > n.l ;
    } ;
};
node x[5010] ;
node y[5010] ;
int ans[5010][2] ;
int max(int i , int j )
{
    return  i > j ? i :j ;
}
bool findAns(node* arr,int dir )
{
    priority_queue<node> que ;
    while (!que.empty()) {
        que.pop() ;
    }
    for(int i = 0 ; i < n ; i++)
    {
        que.push(arr[i]) ;
    }
    int maxx = 1 ;
    while (!que.empty()) {
        node temp = que.top() ; que.pop() ;
        //存在前面的某个点无法覆盖的情形
        if (maxx  > temp.r) {
            return false ;
        }
        //这是区间有重叠的情况,将此区间的最左端右移到maxx得位置,因为小于maxx的位置都不可能在放置任何东西了。
        else if (maxx  > temp.l)
        {
            temp.l = maxx ;
            que.push(temp) ;
            continue ;
        }
        int cur = max(maxx , temp.l) ;
        ans[temp.id][dir] = cur ;
        maxx = cur + 1 ;
    }
    
    return true  ;
}
int main(int argc, const char * argv[]) {
    while (scanf("%d" ,&n),n) {
        for (int i = 0; i < n; i++) {
            scanf("%d%d%d%d" ,&x[i].l,&y[i].l,&x[i].r,&y[i].r) ;
            x[i].id = i ;
            y[i].id = i ;
        }
//        sort(x, x + n) ;
//        sort(y, y+n) ;
        if (findAns(x , 0)) {
            if (findAns(y,1)) {
                for (int i = 0; i < n ; i++) {
                    printf("%d %d\n" , ans[i][0] , ans[i][1]) ;
                 }
            }
            else{
                printf("IMPOSSIBLE\n") ;
            }
        }
        else
        {
            printf("IMPOSSIBLE\n")  ;
        }
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值