Problem Statement
You have NN items and a bag of strength WW. The ii-th item has a weight of wiwi and a value of vivi.
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 WW.
Your objective is to maximize the total value of the selected items.
Constraints
- 1≤N≤1001≤N≤100
- 1≤W≤1091≤W≤109
- 1≤wi≤1091≤wi≤109
- For each i=2,3,...,Ni=2,3,...,N, w1≤wi≤w1+3w1≤wi≤w1+3.
- 1≤vi≤1071≤vi≤107
- WW, each wiwi and vivi are integers.
Input
Input is given from Standard Input in the following format:
NN WW w1w1 v1v1 w2w2 v2v2 : wNwN vNvN
Output
Print the maximum possible total value of the selected items.
Sample Input 1 Copy
Copy
4 6 2 1 3 4 4 10 3 4
Sample Output 1 Copy
Copy
11
The first and third items should be selected.
Sample Input 2 Copy
Copy
4 6 2 1 3 7 4 10 3 6
Sample Output 2 Copy
Copy
13
The second and fourth items should be selected.
Sample Input 3 Copy
Copy
4 10 1 100 1 100 1 100 1 100
Sample Output 3 Copy
Copy
400
You can take everything.
Sample Input 4 Copy
Copy
4 1 10 100 10 100 10 100 10 100
Sample Output 4 Copy
Copy
0
You can take nothing.
题意:第一行两个数分别是物品的数量,和背包的容量。
接下来n行,是每个物品的重量和价值。
求不超过背包容量所能获得的最大价值。
思路:
由于数据比较大所以不能用背包;
由于w1≤wi≤w1+3,可以根据容量分成四种背包,每种背包按价值从大到小排序求出前缀和数组。然后依次枚举每种背包的
数量。
代码:
#include<bits/stdc++.h>
#define ll long long
using namespace std;
vector<ll> a[5];
ll sum1[109];
ll sum2[109];
ll sum3[109];
ll sum4[109];
const bool com(const ll a,const ll b)
{
return a>b;
}
int main()
{
int n;
ll w;
cin>>n;
cin>>w;
ll u1,v1;
ll u,v;
cin>>u1>>v1;
a[1].push_back(v1);
for(int i=2; i<=n; i++)
{
cin>>u>>v;
if(u-u1==0)
{
a[1].push_back(v);
}
else if(u-u1==1)
{
a[2].push_back(v);
}
else if(u-u1==2)
{
a[3].push_back(v);
}
else
{
a[4].push_back(v);
}
}
sort(a[1].begin(),a[1].end(),com);
sort(a[2].begin(),a[2].end(),com);
sort(a[3].begin(),a[3].end(),com);
sort(a[4].begin(),a[4].end(),com);
for(int i=0; i<a[1].size(); i++)
{
if(i==0)
{
sum1[i+1]=a[1][i];
}
else
{
sum1[i+1]=sum1[i]+a[1][i];
}
}
for(int i=0; i<a[2].size(); i++)
{
if(i==0)
{
sum2[i+1]=a[2][i];
}
else
{
sum2[i+1]=sum2[i]+a[2][i];
}
}
for(int i=0; i<a[3].size(); i++)
{
if(i==0)
{
sum3[i+1]=a[3][i];
}
else
{
sum3[i+1]=sum3[i]+a[3][i];
}
}
for(int i=0; i<a[4].size(); i++)
{
if(i==0)
{
sum4[i+1]=a[4][i];
}
else
{
sum4[i+1]=sum4[i]+a[4][i];
}
}
/*for(int i=1;i<=4;i++)
{
cout<<a[i].size()<<endl;
}*/
ll maxx=-1;
for(int i=0;i<=a[1].size();i++)
{
for(int j=0;j<=a[2].size();j++)
{
for(int k=0;k<=a[3].size();k++)
{
for(int g=0;g<=a[4].size();g++)
{
if(u1*i+(u1+1)*j+(u1+2)*k+(u1+3)*g<=w)
{
maxx=max(maxx,sum1[i]+sum2[j]+sum3[k]+sum4[g]);
}
}
}
}
}
cout<<maxx<<endl;
}