Optimal loading problem - greedy algorithm

#include <iostream>
#include <algorithm>

using namespace std;

// 贪心法
// 最优装载问题
void optionalLoad(int *a, int n, int C) {
    sort(a, a + n);
    int retain = C;
    for (int i = 0; i < n; i++) {
        if (a[i] <= retain) {
            cout << a[i] << " ";
            retain -= a[i];
        }
    } 
    COUT << endl; 
} 

int main () {
     the while ( to true ) {
         // n-th object 
        int n-; 
        COUT << " Please enter the total number of objects (exit 0): " ; 
        CIN >> n-;
         IF (! N-) {
             BREAK ; 
        } 
        int C; 
        COUT << " Please enter the total weight of not more than: " ; 
        CIN >> C;
         int * a = new new  int[n-];
         // int NUM;
         //         int A [n-];
         // CIN >> NUM;
         // int * A = new new int [NUM];
         //     Delete [] A; 
        COUT << " are input " n-<< << " th object weight: " ;
         for ( int I = 0 ; I <n-; I ++ ) { 
            CIN >> a [I]; 
        } 
        
        COUT << " optimal load as: " << endl; 
        optionalLoad (a, n, C) ;
    }
    
    return 0;
}

 

Address the following issues with the greedy algorithm

Question: There are a number of containers to be loaded on board a ship loading capacity of c. Wherein the weight of the container i is wi. Optimal loading problems in a case where the load required unrestricted volume, as many containers loaded on the ship.

Example: Suppose c = 20, w = {5,6,7,8,9}, then the output 567

Guess you like

Origin www.cnblogs.com/wxh-blos/p/12093515.html