Algorithm-simple knapsack problem

It used to be " Come, help me see this question ! "

It ’s “ Yeah, there ’s an answer online!

As long as you think, you can become something in your brain. So, did you think ?

table of Contents

Topic-Simple backpack problem

Title description

Input

Output

Sample input

Sample output

Problem solving

Complete code

 Related topics


 

Topic-Simple backpack problem

Title description

 

There is a backpack that can put the weight of the item S, the existing n items, the weight is w1, w2, w3, ... wn. 

Ask if you can choose several of these n items to put in your backpack, so that the sum of the weights is exactly S. 

If there is a choice that meets the conditions, the backpack has a solution, otherwise the backpack problem has no solution.

 

Input

There are multiple lines of input data, including the weight of the placed item is s, the number of items n, and the weight of each item (the input data are all positive integers)

Multiple sets of test data.

Output

For each test instance, if the condition is met, output "YES", if it is not met, output "NO"

Sample input

20 5
1 3 5 7 9

Sample output

YES

 Title link


Problem solving

Using the idea of ​​dynamic programming, weight [1 ... n] is used to represent the weight of each object. After multiple objects are selected, the weight [m] of the object is added to meet the total weight of s, then s-weight [ m] is equal to the sum of the weights of the previously selected objects. When this operation is repeated, s becomes s-weight [m], the number of objects is reduced by 1 on the original basis, and a selected object is weight weight [ n]. Therefore, we can use recursion to determine whether the conditions are met:

if(packet(s - weight[n - 1], n - 1)){
		return true;
	}
else return packet(s,n - 1);

Of course you will encounter an object in front of weight [m] that is not the selected row, so skip this object and make a judgment.

Complete code

#include<iostream>
using namespace std;
int weight[1000];
bool packet(int s,int n){
	if(s == 0) return true;
	if(s < 0 ||(s > 0 && n < 1)){
		return false;
	}
	if(packet(s - weight[n - 1], n - 1)){
		return true;
	}
	else return packet(s,n - 1);
}
int main(){
	int s, n;
	while(cin>>s>>n){
		for(int i = 0; i < n; i++){
			cin>>weight[i];
		}
		if(packet(s,n))
			cout<<"YES"<<endl;
		else cout<<"NO"<<endl;
	}
	return 0;
}

 Related topics

Previous: Algorithm-Coin Changing (minimum number of coins)

 


If you do n’t understand some algorithms, it ’s normal. You should play with your phone for a while and concentrate on understanding for tens of minutes (yes! Tens of minutes! Of course, it ’s for getting started with Xiaobai). Also, you will say "It's so simple!" ——Lynn

Published 19 original articles · praised 239 · 10,000+ views

Guess you like

Origin blog.csdn.net/qq_45703420/article/details/105452823