C language Merge fruit - greedy algorithm

/ * There are several piles of fruit. Every time you move the piles of stuff together to form larger pile. Energy consumption per operation is the total weight of the fruit piles. How to put all the fruit piled up together, consume the least energy? * /

These are the questions, the question we must first understand the subject, every time the array reordered later moved to move together again.

 1 #include<stdio.h>
 2 
 3 int main(){
 4     
 5     int t, n, m = 0;
 6     int i = 0, j = 0;
 7     scanf("%d",&n);
 8     int sum[n];
 9 
10     for(i = 0; i<n;i++){
11         scanf("%d",&sum[i]);
12     }
13     
14     for(i = 0; i<n-1;i++){
15         for(j = 0; j<n-i-1; j++){
16             if(sum[j]>sum[j+1]){
17                 t = sum[j];
18                 sum[j] = sum[j+1];
19                 sum[j+1] = t; 
20             }
21         }
22     }
23     for(i = 1;i<n;++i){
24         sum[i] += sum[i-1];
25         m += sum[i];
26         for(j = i+1;j<n&&sum[j]<sum[j-1];++j){
27             t = sum[j-1];
28             sum[j-1] = sum[j];
29             sum[j] = t;
30         }
31     } 
32     
33     printf("%d",m);
34     
35     return 0;
36 }

 

Guess you like

Origin www.cnblogs.com/wleaf/p/12004005.html