How to use the knapsack problem algorithm in C++
How to use the knapsack problem algorithm in C
The knapsack problem is one of the classic problems in computer algorithms. It involves how to Choose some items to put in your backpack to maximize the total value of the items. This article will introduce in detail how to use the dynamic programming algorithm in C to solve the knapsack problem, and give specific code examples.
First, we need to define the input and output of the knapsack problem. The input includes the weight array wt[] of the item, the value array val[] of the item, and the capacity W of the backpack. The output is choosing which items to put into the backpack to maximize value. The definition is as follows:
int knapSack(int W, int wt[], int val[], int n) { // 动态规划表格 int dp[n+1][W+1]; // 填充动态规划表格 for (int i = 0; i <= n; i++) { for (int j = 0; j <= W; j++) { if (i == 0 || j == 0) dp[i][j] = 0; // 边界条件 else if (wt[i - 1] <= j) dp[i][j] = max(val[i - 1] + dp[i - 1][j - wt[i - 1]], dp[i - 1][j]); else dp[i][j] = dp[i - 1][j]; } } return dp[n][W]; // 返回最大价值 }
In the above code, we use a two-dimensional array dp[][] to represent the state transition table of dynamic programming, where dpi represents the selection of the first i items, and the backpack capacity is j The maximum total value of the case. The specific algorithm is implemented as follows:
- Initialize the first row and column of the two-dimensional array dp[][] to 0, which means that there are no items to choose from or the maximum total value when the capacity is 0 is 0;
Starting from row 1 and column 1, calculate each dpi:
- If the weight of the current item wt[i-1] is less than or equal to the backpack Capacity j, you can choose to put items in or not, and choose the largest total value in both cases;
- If the weight of the current item wt[i-1] is greater than the backpack capacity j, it cannot Put in the current item, the total value is equal to the previous state, that is, dpi-1;
- Finally return dpn, indicating that the first n items are selected and the backpack capacity is W the maximum total value.
The following is a sample code using the knapsack problem algorithm:
#includeusing namespace std; int knapSack(int W, int wt[], int val[], int n) { // 动态规划表格 int dp[n+1][W+1]; // 填充动态规划表格 for (int i = 0; i <= n; i++) { for (int j = 0; j <= W; j++) { if (i == 0 || j == 0) dp[i][j] = 0; // 边界条件 else if (wt[i - 1] <= j) dp[i][j] = max(val[i - 1] + dp[i - 1][j - wt[i - 1]], dp[i - 1][j]); else dp[i][j] = dp[i - 1][j]; } } return dp[n][W]; // 返回最大价值 } int main() { int val[] = {60, 100, 120}; int wt[] = {10, 20, 30}; int W = 50; int n = sizeof(val) / sizeof(val[0]); cout << "最大总价值为:" << knapSack(W, wt, val, n) << endl; return 0; }
Run the above code and the maximum total value of the output result is 220, which means that when the knapsack capacity is 50, The maximum total value you can get by choosing Item 1 and Item 3.
In addition to the above dynamic programming methods, the knapsack problem can also be solved using other methods such as backtracking and greedy algorithms. The above is a detailed introduction on how we use the knapsack problem algorithm in C. I hope it will be helpful to you.
The above is the detailed content of How to use the knapsack problem algorithm in C++. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



PHP algorithm analysis: How to use dynamic programming algorithm to solve the longest palindrome substring problem? Dynamic Programming (Dynamic Programming) is a commonly used algorithm idea that can solve many complex problems. One of them is the longest palindrome substring problem, which is to find the length of the longest palindrome substring in a string. This article will introduce how to use PHP to write a dynamic programming algorithm to solve this problem, and provide specific code examples. Let’s first define the longest palindrome substring. A palindrome string refers to a string that reads the same forward and backward, and the palindrome string

How to use C# to write dynamic programming algorithm Summary: Dynamic programming is a common algorithm for solving optimization problems and is suitable for a variety of scenarios. This article will introduce how to use C# to write dynamic programming algorithms and provide specific code examples. 1. What is a dynamic programming algorithm? Dynamic Programming (DP) is an algorithmic idea used to solve problems with overlapping subproblems and optimal substructure properties. Dynamic programming decomposes the problem into several sub-problems to solve, and records the solution to each sub-problem.

How to use C# to write a knapsack problem algorithm The knapsack problem (Knapsack Problem) is a classic combinatorial optimization problem, which describes a knapsack with a given capacity and a series of items, each item has its own value and weight. The goal is to find an optimal strategy that maximizes the total value of the items packed into the backpack without exceeding the capacity of the backpack. In C#, the knapsack problem can be solved through dynamic programming. The specific implementation is as follows: usingSystem;namespace

How to use the knapsack problem algorithm in C++ The knapsack problem is one of the classic problems in computer algorithms. It involves how to select some items to put into the knapsack under a given knapsack capacity to maximize the total value of the items. This article will introduce in detail how to use the dynamic programming algorithm in C++ to solve the knapsack problem, and give specific code examples. First, we need to define the input and output of the knapsack problem. The input includes the weight array wt[] of the item, the value array val[] of the item, and the capacity W of the backpack. The output is which objects are selected

Memoization is a technique based on dynamic programming used to improve the performance of recursive algorithms by ensuring that a method does not run multiple times on the same set of inputs, by recording the results (stored in an array) for the inputs provided. Memoization can be achieved through a top-down approach that implements recursive methods. Let’s understand this situation through a basic Fibonacci sequence example. 1-D memoization We will consider a recursive algorithm with only one non-constant parameter (only one parameter changes in value), so this method is called 1-D memoization. The following code is for finding the Nth (all terms up to N) in the Fibonacci sequence. Example publicintfibonacci(intn){ &nb

How to solve knapsack problem in PHP using dynamic programming algorithm and get optimal solution? The knapsack problem is one of the classic combinatorial optimization problems in computer science. Given a set of items and the capacity of a knapsack, how to select items to put into the knapsack so as to maximize the total value of the items in the knapsack is the core of the knapsack problem that needs to be solved. Dynamic programming is one of the common methods to solve the knapsack problem. It finally obtains the optimal solution by splitting the problem into sub-problems and saving the solutions to the sub-problems. Below we will explain in detail how to use dynamic programming algorithm in PHP

Detailed explanation of dynamic programming algorithm in PHP Dynamic programming (Dynamic Programming) is an algorithmic idea for solving problems. It solves the overall problem by decomposing the problem into smaller sub-problems and using the results of the solved sub-problems. In PHP, dynamic programming algorithms can be widely used in many fields of computer science and mathematics, such as shortest paths, string matching, and knapsack problems. This article will introduce the principles of dynamic programming algorithm in PHP in detail and provide code examples to illustrate. 1. Dynamic programming calculation

How to use PHP to implement the knapsack problem algorithm. The knapsack problem is a classic combinatorial optimization problem. Its goal is to select a set of items to maximize their total value under a limited backpack capacity. In this article, we will introduce how to use PHP to implement the algorithm of the knapsack problem and provide corresponding code examples. Description of the knapsack problem The knapsack problem can be described in the following way: given a knapsack with a capacity C and N items. Each item i has a weight wi and a value vi. It is required to select some items from these N items such that they
