2014年6月24日 星期二

uva 11039 Building designing

用 Greedy 的方法:
最開始,挑兩種顏色中,最小的先擺下面,再來輪流放該顏色最小可以放得上去。
堆完之後,即為最大高度。


#include <stdio.h>
#include <stdlib.h>

int compare(const void *a, const void* b){
    return *(int *)a - *(int *)b;
}

int main(void){
    int amount, floor;

    int i,j, neg,pos, temp;
    int counter;

    int *nn, *pp;
    nn = malloc(sizeof(int)*500000);
    pp = malloc(sizeof(int)*500000);

    scanf("%d",&amount);
    while(amount--){
        scanf("%d",&floor);
        for(i=0,neg=-1,pos=-1;i<floor;i++){
            scanf("%d",&temp);
            if(temp<0){
                nn[++neg]=temp*(-1);
            }else{
                pp[++pos]=temp;
            }
        }
        qsort(nn,neg+1,sizeof(int),compare);
        qsort(pp,pos+1,sizeof(int),compare);

        i=j=counter=0;
        if(neg>=0&&pos>=0){
            if(pp[i]>nn[j]){
                temp= (-1) * nn[j];
                ++j;
            }else{
                temp=pp[i];
                ++i;
            }
            ++counter;
        }else if(neg>=0 || pos>=0){
            counter=1;
        }
        while(j<=neg&&i<=pos&&temp!=0){
            if(temp>=0){
                while(j<=neg){
                    if(nn[j] > temp){
                        ++counter;
                        temp=nn[j]*(-1);
                        ++j;
                        break;
                    }
                    ++j;
                }
            }else{
                while(i<=pos){
                    if(pp[i] > temp*(-1)){
                        ++counter;
                        temp=pp[i];
                        ++i;
                        break;
                    }
                    ++i;
                }
            }
        }

        if(counter>1){
            if(temp>=0){
                while(j<=neg){
                    if(nn[j] > temp){
                        ++counter;
                        ++j;
                        break;
                    }
                    ++j;
                }
            }else{
                while(i<=pos){
                    if(pp[i] > temp*(-1)){
                        ++counter;
                        ++i;
                        break;
                    }
                    ++i;
                }
            }
        }

        printf("%d\n",counter);
    }

    return 0;
}

沒有留言:

張貼留言