Problem Description
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
Input is given from Standard Input in the following format:
N W
w1 v1
w2 v2
:
wN vNOutput
Print the maximum possible total value of the selected items.
Example
Sample Input 1
4 6
2 1
3 4
4 10
3 4Sample Output 1
11
The first and third items should be selected.Sample Input 2
5 400
3 1 4 1 5Sample Output 2
13
The second and fourth items should be selected.Sample Input 3
4 10
1 100
1 100
1 100
1 100Sample Output 3
400
You can take everything.Sample Input 4
4 1
10 100
10 100
10 100
10 100Sample Output 4
0
You can take nothing.
题意: n 件物品,背包容量为 w,第 i 件物品重量为 wi,价值为 vi,求最大价值
思路:01背包
由于容量 W 最大到 1E9,超出数组范围,因此需要优化
每件物品重量都在 [w1,w1+3] 范围内,因此可以将 w1 提出来, 原来的状态 dp[i][j] 表示前 i 个物品重量为 j 时的最大价值,将 w1 提出来后将 dp[i][j] 改为 dp[i][j][k],表示 前 i 个物品占 k*w1+j 质量时的最大价值,其中 k 表示放进去 k 个物品,j 表示多出来的质量,且由于将 w1 提出来,多出的质量 j 不会超过 300
Source Program
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<string>
#include<cstring>
#include<cmath>
#include<ctime>
#include<algorithm>
#include<utility>
#include<stack>
#include<queue>
#include<vector>
#include<set>
#include<map>
#include<bitset>
#define EPS 1e-9
#define PI acos(-1.0)
#define INF 0x3f3f3f3f
#define LL long long
const int MOD = 1E9+7;
const int N = 500+5;
const int dx[] = {-1,1,0,0,-1,-1,1,1};
const int dy[] = {0,0,-1,1,-1,1,-1,1};
using namespace std;
LL w[N],v[N];
LL dp[N][N][N];
int main(){
LL n,W;
scanf("%lld%lld",&n,&W);
for(int i=1;i<=n;i++)
scanf("%lld%lld",&w[i],&v[i]);
LL w1=w[1];
for(int i=1;i<=n;i++)
w[i]-=w1;
for(int i=1;i<=n;i++){
for(int j=0;j<=n;j++){
for(int k=1;k<=n;k++){
if(j>=w[i]){
dp[i][j][k]=max(dp[i-1][j][k],dp[i-1][j-w[i]][k-1]+v[i]);
}
else{
dp[i][j][k]=dp[i-1][j][k];
}
}
}
}
LL res=0;
for(int j=0;j<=300;j++){
for(int k=0;k<=n;k++){
if(k*w1+j<=W){
res=max(res,dp[n][j][k]);
}
}
}
printf("%lld\n",res);
return 0;
}