【程式解題】2019年4月TOI練習賽新手組 - 滿意度調查 (Survey of Satisfaction) C解法(註解版)

題目請點此


程式碼:

#include <stdio.h>

#include <stdlib.h>

#define SWAP(x,y,t)(t=x,x=y,y=t)


int main(){

int i,j;//loop

long tmp;//用在排序的SWAP

long long  n;//input

long survey[2][10]={0};//各滿意度分數儲存

scanf("%lld",&n);

for(i=0;i<10;++i){

survey[0][i]=i;//把分數存進survey[0][i]

}

while(n){

switch(n%10){//把各分數的個數存進陣列survey[1][]

case 0:

++survey[1][0];

break;

case 1:

++survey[1][1];

break;

case 2:

++survey[1][2];

break;

case 3:

++survey[1][3];

break;

case 4:

++survey[1][4];

break;

case 5:

++survey[1][5];

break;

case 6:

++survey[1][6];

break;

case 7:

++survey[1][7];

break;

case 8:

++survey[1][8];

break;

case 9:

++survey[1][9];

break;

}

n/=10;

}

        //bubble sort,由個數少到多

for(i=9;i>=1;--i){    

for(j=1;j<=i;++j){

if(survey[1][j-1]>survey[1][j]){

SWAP(survey[0][j-1],survey[0][j],tmp);

SWAP(survey[1][j-1],survey[1][j],tmp);

}

}

}

        //bubble sort,讓個數一樣的數值小排前面

        for(i=9;i>=1;--i){

for(j=1;j<=i;++j){

if(survey[1][j-1]==survey[1][j]){

if(survey[0][j-1]<survey[0][j]){

SWAP(survey[0][j-1],survey[0][j],tmp);

SWAP(survey[1][j-1],survey[1][j],tmp);

}

}

}

}

for(j=9;j>=0;--j){//輸出滿意度

if(survey[1][j]) printf("%d ",survey[0][j]);

}

return 0;

}

留言

這個網誌中的熱門文章

【程式解題】 ZeroJudge a038數字翻轉 C解法(逐行註解)