本文主要是介绍金银岛(贪心算法实操),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目
解答
#include <stdio.h>
#include <stdlib.h>
struct Kuangshi {int weight;int money;double danjia;
};
int cmp(const void *a, const void *b) {struct Kuangshi *aa = (struct Kuangshi *)a;struct Kuangshi *bb = (struct Kuangshi *)b;return (((aa->danjia) < (bb->danjia)) ? 1 : -1);
}
int main() {int k, w, s;int i, j;double Output[100];scanf("%d", &k); //组数for ( i = 0; i < k; i++) {scanf("%d", &w); //口袋上限scanf("%d", &s); //矿石种类Kuangshi kuangshi[s];for ( j = 0; j < s; j++) { //录入scanf("%d %d", &kuangshi[j].weight, &kuangshi[j].money);kuangshi[j].danjia = (double)kuangshi[j].money / (double)kuangshi[j].weight;}qsort(kuangshi, s, sizeof(kuangshi[0]), cmp); //从大到小排序int shengyu = w; //剩余空间j = 0;Output[i]=0;do {shengyu -= kuangshi[j].weight;if(shengyu<0){Output[i]=Output[i]+(shengyu+kuangshi[j].weight)*kuangshi[j].danjia;}else Output[i] += kuangshi[j].money;j++;} while (shengyu > 0&&j<s);}for(int i=0;i<k;i++){printf("%.2lf\n",Output[i]);}return 0;
}
这篇关于金银岛(贪心算法实操)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!