1068 Find More Coins (30point (s)) require two brush * 01 knapsack problem dynamic programming

The basic idea:

A typical 01 knapsack problem;

 

key point:

Follow summary;

 

#include<iostream>
#include<stdlib.h>
#include<stdio.h>
#include<vector> 
#include<string>
#include<math.h>
#include<algorithm>
#include<cstring>
#include<map>
#include<queue>
#include<set>
#include<stack>
using namespace std;

const  int maxn = 10010 ;

int n, m;
int vec[maxn];
int dp[maxn];
bool choice[maxn][maxn];

bool cmp(int a,int b) {
    return a > b;
}

int main () {
    cin >> n >> m;
    //int a;
    for (int i = 1; i <= n; i++) {
        cin >> vec[i];
    }
    Sort (VEC + . 1 , n-+ + VEC . 1 , CMP);
     // initialize array dp;
     // m corresponds to the capacity / value; 
    for ( int I = 0 ; I <= m; I ++ ) {
         // representatives zero elements put before does not hold should be 0; 
        DP [I] = 0 ;
    }
    for ( int I = . 1 ; I <= n; I ++ ) {
         // first n elements into the cycle start; 
        for ( int V = m; V> VEC = [I]; V - ) {
             // If placed; 
            IF (DP [V] <DP = [V - VEC [I]] + VEC [I]) {
                 // If better placed; 
                Choice [I] [V] = . 1 ; // Representative into 
                DP [V] = max (DP [V], DP [V - VEC [I]] + VEC [I]); // not into, or placed; 
            }
             the else {
                Choice [I] [V] = 0 ; // Representative not put 
            }
        }
    }
    IF (DP [m] =! m) {
         // if not produce the optimal solution; 
        COUT << " No Solution " << endl;
    }
    the else {
         // if the optimal solution; 
        int K = n-, NUM = 0 , V = m;
         BOOL In Flag = to true ;
         the while (K> = 0 ) {
             IF (Choice [K] [V] == . 1 ) {
                 // selection; 
                IF (In Flag) {
                    cout << ith [k];
                    flag = false;
                }
                else {
                    cout <<" "<< vec[k];
                }
                in - = vec [i];
            }
            k--;
        }
    }
    return 0;
}

 

Guess you like

Origin www.cnblogs.com/songlinxuan/p/12357908.html