D - Simple Knapsack(思维+讨论)

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
#define ll long long
using namespace std;
vector 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

 

你可能感兴趣的:(例题,思维好题)