動態規劃 01背包 c演算法

來源:互聯網
上載者:User

#include <stdio.h>
#include <stdlib.h>

#define N 5
#define C 10

void knapsack(int w[N], int v[N], int m[][C]);
void traceback(int m[][C], int w[N], int x[N]);

void knapsack(int w[N], int v[N], int m[][C])
{
    int n = N;
    int c = C;

    int i, j;
    for(i = 0; i < c; i++){
        if(i < w[0]){
            m[0][i] = 0;
        }
        else{
            m[0][i] = v[0];
        }
       
    }

    for(i = 1; i< n-1; i++){
        for(j = 0; j< c; j++){
            if(j > w[i]){
                m[i][j] = max(m[i-1][j], v[i] + m[i-1][j-w[i]]);
            }
            else{
                m[i][j] = m[i-1][j];
            }
        }
    }
    m[n-1][c-1] = m[n-2][c-1];
    if(c > w[n-1]){
        m[n-1][c-1] = max(m[n-2][c-1], v[n-1] + m[n-2][c-w[n-1]]);
    }

}

void traceback(int m[][C], int w[N], int x[N])
{
    int j = C;
    int i;
    for(i = N-1; i >= 1; i--){
        if(m[i][j-1] == m[i-1][j-1]){
            x[i] = 0;
        }
        else{
            j = j - w[i];
            x[i] = 1;

        }
    }
    if(j > 0){
        x[0] = 1;
    }
    else{
        x[0] = 0;
    }

}

int main()
{
    int w[N] = {2, 2, 6, 5, 4};
    int v[N] = {6, 3, 5, 4, 6};
    int x[N] = {0};
    int m[N][C] = {{0}};
    int i;
    knapsack(w, v, m);
    traceback(m, w, x);

    for(i=0; i< N; i++)
    {
      printf("%d ", x[i]);
    }
    printf("/n");

    system("pause");
    return 0;
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.