2020-2-5新生赛

01背包

题目描述

You have N items and a bag of strength W. The i-th item has a weight of wi and a value of vi.
You will select some of the items and put them in the bag. Here, the total weight of the selected items needs to be at most W.
Your objective is to maximize the total value of the selected items.

Constraints
1≤N≤100
1≤W≤109
1≤wi≤109
For each i=2,3,…,N, w1≤wi≤w1+3.
1≤vi≤107
W, each wi and vi are integers.

输入

Input is given from Standard Input in the following format:
N W
w1 v1
w2 v2
:
wN vN

输出

Print the maximum possible total value of the selected items.

样例输入

4 6
2 1
3 4
4 10
3 4

样例输出

11

提示

The first and third items should be selected.

一看这道题就是背包问题撒,但是数据太大,我就放弃了,用的点辐射做的,但是这样肯定超时了,

搜了之后,发现是01背包,好吧,是知识漏洞,但是今天dfs写的好。。。

第一个是错的

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
int n,w;
int A[105],B[105],vis[105];
long long int sum=0;
void dfs(int wi,long long int money)
{
    if(wi<w)
    {
        sum=max(sum,money);
        for(int i=1;i<=n;i++)
        {
            if(vis[i]==0)
            {
               if(wi+A[i]<=w)
               {
                   vis[i]=1;
                   dfs(wi+A[i],money+B[i]);
                   vis[i]=0;
               }
            }
        }
    }
    else if(wi==w)
    {
        sum=max(sum,money);
    }
}
int main()
{
  scanf("%d %d",&n,&w);
  for( int i=1;i<=n;i++)
    scanf("%d %d",&A[i],&B[i]);
   dfs(0,0);
   printf("%lld",sum);


}

正确的在这


#include <bits/stdc++.h>

using namespace std;

typedef long long ll;

const ll maxn=110;

ll dp[maxn][maxn*3];

ll n,s,w[maxn],v[maxn];

 

int main(){

    cin>>n>>s;

    for (int i=1; i<=n ;i++)

        cin>>w[i]>>v[i];

    w[0]=w[1]-1;

    ll sum=0;

    for (int i=1; i<=n ;i++) w[i]-=w[0],sum+=w[i];

    ll ans=0;

 

    for (int i=1; i<=n ;i++){

        for (int j=i;j >=1;j--){

            for (int k=sum;k>=w[i];k--){

                dp[j][k]=max(dp[j][k],dp[j-1][k-w[i]]+v[i]);

                if(1ll*j*w[0]+k<=s) ans=max(dp[j][k],ans);

            }

        }

    }

 

    cout<<ans<<endl;

    return 0;

}
发布了32 篇原创文章 · 获赞 1 · 访问量 1345

猜你喜欢

转载自blog.csdn.net/QXK_Jack/article/details/104188886