Codeforces 1132 problem E Knapsack —— dp求特大数据背包

You have a set of items, each having some integer weight not greater than 8. You denote that a subset of items is good if total weight of items in the subset does not exceed W.

You want to calculate the maximum possible weight of a good subset of items. Note that you have to consider the empty set and the original set when calculating the answer.

Input
The first line contains one integer W (0≤W≤1018) — the maximum total weight of a good subset.

The second line denotes the set of items you have. It contains 8 integers cnt1, cnt2, …, cnt8 (0≤cnti≤1016), where cnti is the number of items having weight i in the set.

Output
Print one integer — the maximum possible weight of a good subset of items.

Examples
inputCopy
10
1 2 3 4 5 6 7 8
outputCopy
10
inputCopy
0
0 0 0 0 0 0 0 0
outputCopy
0
inputCopy
3
0 4 1 0 0 9 8 3
outputCopy
3

题意:

给你大小为1到8的物体的数量,让你求容量为w可以装下的最大物体体积。

题解:

他这个有一个性质,9=8+1=7+2=7+1+1,所以枚举每个物品的时候只需要枚举8次即可,如果再减就没有意义了。

#include
using namespace std;
#define ll long long
ll a[10],w,ans;
void dfs(ll pos,ll sum)
{
    if(pos>8)
    {
        ans=max(ans,sum);
        return ;
    }
    ll num=min(a[pos],(w-sum)/pos);
    for(int i=1;i<=8&&num>=0;i++)
        dfs(pos+1,sum+pos*num),num--;
}
int main()
{
    scanf("%lld",&w);
    for(int i=1;i<=8;i++)
        scanf("%lld",&a[i]);
    dfs(1,0);
    printf("%lld\n",ans);
    return 0;
}

你可能感兴趣的:(想法,dp)