(White Book Training Program) ultraviolet A 11134 Fabled Rooks (Greedy), 11134 fabled
Subject address: Ultraviolet A 11134
This is because the rows and columns are irrelevant and have no impact on each other. Therefore, you can separate rows or columns for calculation. This is equivalent to converting to selecting n different integers in the period [1, n], so that the I-th integer is within the Closed range [Li, Ri. This is a greedy problem. However, note that you cannot sort by left endpoint first, then by right endpoint, and then try to put it on the left, such as (), (), (). This is wrong, sort by the right endpoint as the primary keyword, and then by the Left endpoint as the secondary keyword. All the methods on the Internet use the priority queue instead of the number selected each time .. I don't feel it is necessary to do this .. You only need to replace the sorting keyword.
The Code is as follows:
#include <iostream>#include <cstdio>#include <string>#include <cstring>#include <stdlib.h>#include <math.h>#include <ctype.h>#include <queue>#include <map>#include <set>#include <algorithm>using namespace std;int a[6000], b[6000], _hash[6000];struct node{ int l, r, num;}x[100000], y[100000];int cmp(node x, node y){ if(x.r==y.r) return x.l<y.l; return x.r<y.r;}int main(){ int n, i, j, flag, z; while(scanf("%d",&n)!=EOF&&n) { for(i=0;i<n;i++) { scanf("%d%d%d%d",&x[i].l,&y[i].l,&x[i].r,&y[i].r); x[i].num=i; y[i].num=i; } memset(_hash,0,sizeof(_hash)); sort(x,x+n,cmp); sort(y,y+n,cmp); z=0; for(i=0;i<n;i++) { flag=0; for(j=x[i].l;j<=x[i].r;j++) { if(!_hash[j]) { a[x[i].num]=j; _hash[j]=1; flag=1; break; } } if(!flag) { z=1; break; } } if(z) { printf("IMPOSSIBLE\n"); continue ; } memset(_hash,0,sizeof(_hash)); z=0; for(i=0;i<n;i++) { flag=0; for(j=y[i].l;j<=y[i].r;j++) { if(!_hash[j]) { b[y[i].num]=j; _hash[j]=1; flag=1; break; } } if(!flag) { z=1; break; } } if(z) { printf("IMPOSSIBLE\n"); continue ; } for(i=0;i<n;i++) { printf("%d %d\n",a[i],b[i]); } } return 0;}