链接:http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=24&page=show_problem&problem=2075
题目大意:
在一个n*n的棋盘上放置n个车,使得它们之间都不能互相攻击(任意两个车都不能同行或同列),并且,对于第i个车,限制它只能放在一个矩形区域内,(xli, yli),这个矩形的左上角顶点坐标是(xli, yli),右下角顶点坐标是 (xri, yri), 1 ≤ i ≤ n, 1 ≤ xli ≤ xri ≤ n, 1 ≤ yli ≤ yri ≤ n.
分析:行和列可以分开考虑,分别贪心求解,优先放置r最小的,最后再组合起来。
#include <queue> #include <cstdio> #include <algorithm> #include <iostream> #define MAXN 5002 using namespace std; int n,ans[MAXN][2]; struct thing { int l,r,num; friend bool operator < (const thing a,const thing b) { return a.r > b.r; } } row[MAXN],col[MAXN]; bool camp(const thing a,const thing b) { return a.l < b.l; } bool deal(const thing a[MAXN],int pos) { priority_queue <thing> q; int now = 0; for(int i = 1;i <= n;i++) { while(a[now+1].l <= i && now < n) q.push(a[++now]); if(q.empty()) return false; thing u = q.top(); q.pop(); if(u.r < i) return false; ans[u.num][pos] = i; } return true; } int main() { while(scanf("%d",&n) && n) { for(int i = 1;i <= n;i++) { scanf("%d%d%d%d",&row[i].l,&col[i].l,&row[i].r,&col[i].r); row[i].num = col[i].num = i; } sort(row+1,row+1+n,camp); sort(col+1,col+1+n,camp); if(deal(row,0) && deal(col,1)) { for(int i = 1;i <= n;i++) printf("%d %d\n",ans[i][0],ans[i][1]); } else printf("IMPOSSIBLE\n"); } }