atcoder Educational DP Contest x-Tower

Question:
There are n piles of items, and each pile of items has three values, weight w, load-bearing s, and value v. These items can be stacked. The total weight stacked on top of each item must be less than or equal to its load-bearing capacity. Ask for stacking What is the maximum total value of your items.

Solution:
Assuming that there are only two items w1, s1 / w2, s2, if the first item is on top, the remaining weight is s2-w1, otherwise it is s1-w2.
If s2-w1>s1-w2, that is, s2+w2>s1+w1, think greedily, we must choose a solution that can put more weight. From this we can draw a conclusion, sort s+w in ascending order, put the big choice below, and finally the 01 knapsack problem.

Code:

#include<bits/stdc++.h>
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<queue>
#include<map>
#include<stack>
#include<set>
#define iss ios::sync_with_stdio(false)
using namespace std;
typedef unsigned long long ull;
typedef long long ll;
const int MAXN=1e3+5;
const int mod=1e9+7;
struct node
{
    
    
    int w,s,v;
}f[MAXN];
ll dp[10000005];
bool cmp(node a,node b)
{
    
    
    return a.w+a.s<b.w+b.s;
}
const ll inf=-0x3f3f3f3f3f;
int main()
{
    
    
    int n;
    cin>>n;
    for(int i=1;i<=n;i++)
    {
    
    
        cin>>f[i].w>>f[i].s>>f[i].v;
    }
    sort(f+1,f+1+n,cmp);
    memset(dp,inf,sizeof dp);
    dp[0]=0;
    for(int i=1;i<=n;i++)
    {
    
    
        for(int j=f[i].s;j>=0;j--)
        {
    
    
            dp[j+f[i].w]=max(dp[j+f[i].w],dp[j]+f[i].v);
        }
    }
    ll ans=0;
    for(int i=0;i<=10000000;i++)
    {
    
    
        ans=max(ans,dp[i]);
    }
    cout<<ans<<endl;
}

Guess you like

Origin blog.csdn.net/weixin_45755679/article/details/112998708