Boxing dfs backtrace

A. Boxes (boxes) [Discussion]
Description
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 (positive Integer).
It is required to take several items from n items and put them into the box to minimize the remaining space of the box.


The capacity of the input box v the
number of items n the
next n lines, respectively representing the volume of these n items

Output
box remaining space

Samples
Input Copy
24
6
8
3
12
7
9
7
Output
0

#include<bits/stdc++.h>
using namespace std;
#define IN -1e6
#define INT 1e6
const int maxn=1e8;
int res=1;
typedef long long ll;
set <int> s;

typedef struct st{
    
    
    int x;
    int y;
    int z=0;
}ss;
int min1(int a,int b)
{
    
    
    if(a<b)
        return a;
    return b;
}
int cmp(char a,char b)
{
    
    
    return a>b;
}
int n;
int v;
int sheng=100000;
int sum=0;
int a[100];
void dfs(int t)
{
    
    
    if(t==n+1)
    {
    
    

        if(sheng>sum&&sum<=v)
            {
    
    
                if(v-sum<sheng)
                    sheng=v-sum;
            }
            return;
    }
    sum+=a[t];
    dfs(t+1);
    sum-=a[t];
    dfs(t+1);

}

int main()
{
    
    

   cin>>v>>n;
    for(int i=1;i<=n;i++)
    {
    
    
        cin>>a[i];
    }
    dfs(1);
    cout<<sheng;
    return 0;
}

Guess you like

Origin blog.csdn.net/qq_52172364/article/details/112473340
dfs