Recursion 5: [SSL] 1169 Packing problem-more on March 6, 2021

Recursion 5: [SSL] 1169 boxing problem

topic:

There is a box with a capacity of V (a positive integer, 0<=V<=20000), and there are n items (0<n<=30, and each item has a volume (a positive integer).

It is required that among the n items, any number of them can be put into the box, so that the remaining space of the box is minimized.

Input example
24
6
8 
3
12
7
9
7

Output sample
0

Ideas:

This topic is actually a good idea, but because the data is too large, attention should be paid to optimization.
Thinking hard, it is not difficult to find that there are only 2 methods for a box, put it or not. For example, use 1 to put and 0 to not put. Assuming there are 3 boxes, there are 8 ways:
111
110
101
100
011
010
001
000
So we can conclude that n boxes have 2 to the power of n Planting method.
However, the maximum n is 30, and 2^30 is more than one billion. If you try one by one, it will inevitably time out, so you need to optimize. If recursion is regarded as a tree, then as long as the condition is found, a part of the branches and leaves can be cut off, so that the number of runs can be reduced a lot, because the title states that the space in the box should be reduced as much as possible, so each recursion When judging, as long as all the remaining volume of me plus the space occupied in the box is less than or equal to the maximum value I found so far, then this recursion can end and return to the previous level.

Code:

#include<bits/stdc++.h>
using namespace std;
int n,v,a[50],h,b[50];

void dg(int p,int s,int sy)
{
    
    
	if(p>n)
	{
    
    
		h=max(h,s);
		return ;
	}
	if(s+b[n]-b[p-1]<=h)
		return ;
	if(sy>=a[p])
		dg(p+1,s+a[p],sy-a[p]);
	dg(p+1,s,sy);
}
int main()
{
    
    
	cin>>v>>n;
	for(int i=1;i<=n;i++)
	{
    
    
		cin>>a[i];
		b[i]=b[i-1]+a[i];
	}
	dg(1,0,v);
	cout<<v-h;
	return 0;
} 

Guess you like

Origin blog.csdn.net/SSL_wyd/article/details/114437070