C语言合并果子-贪心算法
/*有几堆水果。每次你把两堆东西移到一起,形成更大的一堆。每个动作消耗的能量是两堆水果的总重量。如何把所有的水果堆在一起,消耗最少的能量?*/
以上是题目,该题首先要读懂题目,每次移到一起以后都要将数组重新排序再次移动。
#include<stdio.h> int main(){ int t, n, m = 0; int i = 0, j = 0; scanf("%d",&n); int sum[n]; for(i = 0; i<n;i++){ scanf("%d",&sum[i]); } for(i = 0; i<n-1;i++){ for(j = 0; j<n-i-1; j++){ if(sum[j]>sum[j+1]){ t = sum[j]; sum[j] = sum[j+1]; sum[j+1] = t; } } } for(i = 1;i<n;++i){ sum[i] += sum[i-1]; m += sum[i]; for(j = i+1;j<n&&sum[j]<sum[j-1];++j){ t = sum[j-1]; sum[j-1] = sum[j]; sum[j] = t; } } printf("%d",m); return 0; }
相关推荐
Tips 2020-11-12
troysps 2020-08-18
Eduenth 2020-07-17
RememberMePlease 2020-06-26
yishujixiaoxiao 2020-06-16
Happyunlimited 2020-06-11
RememberMePlease 2020-06-07
从零开始 2020-05-31
路漫 2020-05-07
Happyunlimited 2020-05-01
从零开始 2020-04-30
ustbfym 2020-04-30
清溪算法 2020-04-22
baike 2020-04-15
pengkingli 2020-03-28
baike 2020-03-27
shawsun 2020-02-26
faiculty 2020-02-24
ipqtjmqj 2020-01-23