# 分享一道百度筆試程序題

``````#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int n = 0;          //禮物總數
int K = 0;          //要留下來的禮物數
int num = 0;        //要留下來的禮物喜好值之和

int * val = NULL;   //所有禮物喜好值數組指針

int main(void)
{
int i,x,y,temp;

//輸入禮物總數量
printf("present quantity(>0): ");
scanf("%d", &n);
printf("M will get present: n = %d !\n", n);

//輸入要留下來的禮物數量
printf("leave quantity(>0 && <=n): ");
scanf("%d", &K);
printf("M will leave present: K = %d !\n\n", K);

//分配所有禮物喜好值數組內存空間，並初始化爲0
val = (int *)calloc(n, sizeof(int));
if(val == NULL)
{
printf("calloc failed!!!!!!\n");
return -1;
}

//初始化隨機數種子
srand((unsigned)time(NULL));
for(i = 0; i < n; i++)
{
//隨機生成一個0~100的禮物喜好值
val[i] = (rand() % 100);
printf("%d present, val: %d \n", (i + 1), val[i]);

//如果收到的禮物數量還沒有超過要留下來的禮物數量
if(i < K)
{
//那麼喜好值之和就等於目前所有禮物喜好值之和
num += val[i];
}
//如果收到的禮物數量超過了要留下來的禮物數量
else
{
//對目前所有禮物按照從大到小喜好值排序
for(x = 0; x < (i + 1); x++)
{
for(y = (x + 1); y < (i + 1); y++)
{
if(val[y] > val[x])
{
temp = val[y];
val[y] = val[x];
val[x] = temp;
}
}
}

num = 0;    //重置喜好值之和

//打印排序結果,並計算目前要留下來的禮物喜好值之和
printf("now rank: ");
for(x = 0; x < (i + 1); x++)
{
if(x < K)   //只需要喜好值最大的 K 個禮物
{
num += val[x];
}
printf("%d ", val[x]);
}
printf("\n");
}

//打印目前要留下來的禮物的喜好值之和
printf("leave present total val: num = %d \n\n", num);
}

free(val);      //釋放禮物喜好值數組內存空間
val = NULL;

return 0;
}``````