Red Huang

Red Huang

背包問題

讓背包裡面的物品總價值最大

  1. const int N = 100, W = 100000;

  2. int cost[N], weight[N];

  3. int c [W + 1];   // 只需要一條陣列就夠了

  4. void knapsack(int n, int w)

  5. {

  6.     memset(c, 0, sizeof(c));

  7.     for (int i = 0; i < n; ++i)

  8.         for (int j = w; j - weight [i] >= 0; --j)    // 由後往前

  9.             c[j] = max(c[j], c[j - weight[i]] + cost[i]);

  10.     cout << "最高的價值為" << c [w];

  11. }

載入中......
此文章數據所有權由區塊鏈加密技術和智能合約保障僅歸創作者所有。