2014/03/03

[UVa] 11321 Sort! Sort!! And Sort!!!


solution:自行修改cmp function
             對於理解qsort滿有幫助的一題



http://uva.onlinejudge.org/external/113/11321.html
#include<stdio.h>
#include <stdlib.h>

typedef struct data{
    int num;
    int remainder;
}Data;
int cmp(const void *a,const void *b);


int main(void){
    int n,m,i;
    while (scanf("%d%d",&n,&m)==2 &&n&&m) {
        Data data[n];
        for (i = 0; i < n; i++) {
            scanf("%d",&data[i].num);
            data[i].remainder = data[i].num % m;
        }
        qsort(data, n, sizeof(data[0]), cmp);
        printf("%d %d\n",n,m);
        for (i=0;i<n; i++) {
            printf("%d\n",data[i].num);
        }
    }
    printf("0 0\n");
    return 0;
}

int cmp(const void *a,const void *b){
    Data c,d;
    c = *(Data*)a;
    d = *(Data*)b;
    if (c.remainder != d.remainder)
        return c.remainder>d.remainder?1:-1;
    else{
        if(c.num%2==0 && d.num%2==0){  
            if (c.num != d.num)
                return c.num>d.num?1:-1;  //若都是偶數,較小的排在前面,則回傳值依舊
            return 0;
        }
        else if ((c.num%2==1||c.num%2==-1) && (d.num%2==1||d.num%2==-1)){
            if (d.num != c.num)
                return c.num>d.num?-1:1; //若都是奇數,較大的排在前面,則回傳值顛倒
            return 0;
        } //以下一奇一偶 奇數排在前面
        else if ((c.num%2==1||c.num%2==-1) && d.num%2==0){
            return -1;  //c為奇數d為偶數,回傳-1維持cd順序
        }
        else
            return 1;   //d為奇數c為偶數,回傳1順序變dc
    }
}