Untitled
unknown
c_cpp
3 years ago
1.4 kB
11
Indexable
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define min(a, b) ((a<b) ? a : b)
typedef struct{
char name[35];
int occu, age;
}Cat;
int cmp(const void* a, const void* b);
int occu_alt(char* a);
int main(){
int N, M;
while(scanf("%d %d ", &N, &M) != EOF){
Cat* cat = (Cat*)malloc(sizeof(Cat) * N);
for(int i=0; i<N; i++){
char occu[15] = {0};
int age;
scanf("%s %s %d", cat[i].name, occu, &cat[i].age);
cat[i].occu = occu_alt(occu);
}
qsort(cat, N, sizeof(Cat), cmp); // 排序貓貓
for(int i=0; i<min(N, M); i++){
printf("%s\n", cat[i].name);
}
free(cat); // 記得free
}
}
int cmp(const void* a, const void* b){
Cat aa = *(Cat*)a;
Cat bb = *(Cat*)b;
if(aa.occu != bb.occu) return aa.occu - bb.occu; // 職業優先序(0-7)
if(aa.age != bb.age) // 年齡排序(第4個職業由小到大 其他大到小)
return (aa.occu == 4) ? (aa.age - bb.age) : (bb.age - aa.age);
return strcmp(aa.name, bb.name); // 同齡比名字(a-z)
}
int occu_alt(char* a){ // 把職業字串轉成數字(0-7)
char occus[] = "enkwamdl";
for(int i=0; i<8; i++)
if(a[0] == occus[i]) return i;
}
Editor is loading...