Cookie Monster

mail@pastecode.io avatar
unknown
c_cpp
2 years ago
2.9 kB
2
Indexable
Never
//Cookie Monster

#include <stdio.h>
#include <string.h>
#define MAXN 10000
#define MAXLEN 10000

int n, k, cnt = 0, num = 0;//cnt為有幾列數字
int ans[MAXN] = {0}, cnt_7[MAXN] = {0};
char tmp[MAXN], str_hex[MAXN], str_dec[MAXN], d[MAXN][MAXLEN];
//d為把數字換為10進位的字串

int cmp_1(int a, int b){
    if(cnt_7[a] < cnt_7[b]) return 1;
    else if(cnt_7[a] > cnt_7[b]) return -1;
    else{//a和b有相同數量的7
        if(strlen(d[a]) < strlen(d[b])) return 1;
        else if(strlen(d[a]) > strlen(d[b])) return -1;
        else{
            int res = strcmp(d[a], d[b]);//若d[a]>d[b] 則 res>0
            if(res < 0) return 1;
            else if(res > 0) return -1;
            else return 0; //d[a]和d[b]是一樣的字串
        }
    }
}

int cmp_2(int a, int b){
    if(strlen(d[a]) > strlen(d[b])) return 1;
    else if(strlen(d[a]) < strlen(d[b])) return -1;
    else return strcmp(d[a], d[b]);
}

void bubble_sort1(){//由大排到小(7的多的 或 字串數字大的)
    for(int i = 0; i < cnt; i++){
        for(int j = i; j < cnt; j++){
            if(cmp_1(ans[i], ans[j]) > 0){
                int temp = ans[i];
                ans[i] = ans[j];
                ans[j] = temp;
            }
        }
    }
}

void bubble_sort2(){//把前k個餅乾由小排到大
    for(int i = 0; i < k; i++){
        for(int j = i; j < k; j++){
            if(cmp_2(ans[i], ans[j]) > 0){
                int temp = ans[i];
                ans[i] = ans[j];
                ans[j] = temp;
            }
        }
    }
}

void find_ans(){
    for(int i = 0; i < cnt; i++){
        ans[i] = i;
    }
    bubble_sort1();
    bubble_sort2();
    for(int i = 0; i < k; i++){
        printf("%s\n", d[ans[i]]);
    }
}

int hex_to_dec(int l, int r){
    num = 0;

    strncpy(str_hex, tmp + l, r - l);
    sscanf(str_hex, "%x", &num);//將str_hex中的數字用16進位的方式存入num
    sprintf(str_dec, "%d", num);//將num轉換為10進位存入str_dec中
    strcat(d[cnt], str_dec);
    memset(str_hex, '\0', MAXN);
    memset(str_dec, '\0', MAXN);
}

int main(){
    
    scanf("%d%d", &n, &k);
    for(int i = 0; i < n; i++){
        int index = 0;
        memset(tmp, '\0', MAXN);
        scanf("%s", tmp);
        for(int j = 0; j < strlen(tmp); j++){
            if(tmp[j] == '|' || j == strlen(tmp) - 1){
                if(j == strlen(tmp)-1) j = strlen(tmp);
                //printf("index1 = %d, index2 = %d\n", index, j);
                hex_to_dec(index, j);
                index = j + 1;
            }
        }
        for(int k = 0; k < strlen(d[cnt]); k++){//算7的這層迴圈不可放在迴圈j中,不然會重複計算
            if(d[cnt][k] == '7'){
                cnt_7[cnt]++;
            }
        }
        cnt++;
    }
    find_ans();
}