⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 recursivedpknapsack.cpp

📁 datastucutre and algorithms, application, in C
💻 CPP
字号:
// dynamic programming recursive knapsack

#include <iostream>
#include <math.h>

using namespace std;

// global variables
int *profit;
int *weight;
int numberOfObjects;

int f(int i, int theCapacity)
{// Return f(i,theCapacity).
   if (i == numberOfObjects)
      return (theCapacity < weight[numberOfObjects])
              ? 0 : profit[numberOfObjects];
   if (theCapacity < weight[i])
      return f(i + 1, theCapacity); 
   return max(f(i + 1, theCapacity),
               f(i + 1, theCapacity - weight[i]) + profit[i]);
}

void main(void)
{
   cout << "Enter number of objects and knapsack capacity" << endl;
   int knapsackCapacity;
   cin >> numberOfObjects >> knapsackCapacity;
   profit = new int [numberOfObjects + 1];
   weight = new int [numberOfObjects + 1];

   for (int i = 1; i <= numberOfObjects; i++)
   {
      cout << "Enter profit and weight of object " << i << endl;
      cin >> profit[i] >> weight[i];
   }

   cout << "Optimal value is " << f(1, knapsackCapacity) << endl;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -