(白書訓練計劃)UVa 11134 Fabled Rooks(貪心)

來源:互聯網
上載者:User

標籤:acm   c語言   演算法   編程   

題目地址:UVa 11134

這題因為行與列是無關的,互無影響的。所以可以將行或列分開來計算。這就相當於轉化成了在期間[1,n]內選擇n個不同的整數,使得第i個整數在閉區間[Li,Ri]內。這就轉換成了一個貪心問題了。但是注意不能先按照左端點排序,再按右端點排序,然後盡量往左邊放,比如,(1,1),(1,3),(2,2),這樣是不對的,應該按右端點為主關鍵字排序,再按左端點為次關鍵字排序。看到網上的方法全都是用每次選一個數後,都要在後面的區間中刪去這個數,還要用到優先隊列。。感覺沒必要這樣做。。只要把排序關鍵字換換就可以了。

代碼如下:

#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;}


(白書訓練計劃)UVa 11134 Fabled Rooks(貪心)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.