【UVa】10341-Solve it!

繼續閱讀

廣告

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

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

http://uva.onlinejudge.org/external/113/11321.html
#include
#include

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

[UVa] 10763 Foreign Exchange

Note:
     用到qsort然後兩兩對消

http://uva.onlinejudge.org/external/107/10763.html
#include
#include

int cmp(const void *s1,const void *s2){
return *(int*)s1-*(int*)s2;
}

int main(void){
int n,i,count;
while (scanf("%d",&n)!=EOF && n) {
count
= 0;
int array[2*n];
for (i = 0;i < 2*n;i++)
scanf
("%d",&array[i]);
qsort
(array, 2*n, sizeof(int), cmp);
for (i = 0; i < 2*n; i+=2) {
if (array[i]!=array[i+1])
count
++;
}
if (count==0)
printf
("YES\n");
else
printf
("NO\n");
}
return 0;
}

UVa 11462 Age Sort

Note:

Use qsort in
http://uva.onlinejudge.org/external/114/11462.html
#include
#include

int cmp(const void *s1, const void *s2);

int main(void){
int n = 0,i;
int array[2000005];
while (scanf("%d",&n)!=EOF && n!=0) {
for (i = 0; i < n; i++)
scanf
("%d",&array[i]);

qsort
(array, n, sizeof(int), cmp);
printf
("%d",array[0]);
for (i = 1; i < n; i++) {
printf
(" %d",array[i]);
}
printf
("\n");
}

return 0;
}

int cmp(const void *s1, const void *s2){
return *(int *)s1 - *(int *)s2;
}