您的位置:首页 > 其它

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

2015-08-13 14:25 459 查看
题目大意:给定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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: