CodeForces808E- Selling Souvenirs(背包)

Description
After several latest reforms many tourists are planning to visit Berland, and Berland people understood that it’s an opportunity to earn money and changed their jobs to attract tourists. Petya, for example, left the IT corporation he had been working for and started to sell souvenirs at the market.
This morning, as usual, Petya will come to the market. Petya has n different souvenirs to sell; ith souvenir is characterised by its weight wi and cost ci. Petya knows that he might not be able to carry all the souvenirs to the market. So Petya wants to choose a subset of souvenirs such that its total weight is not greater than m, and total cost is maximum possible.
Help Petya to determine maximum possible total cost.

Input
The first line contains two integers n and m (1 ≤ n ≤ 100000, 1 ≤ m ≤ 300000) — the number of Petya’s souvenirs and total weight that he can carry to the market.
Then n lines follow. ith line contains two integers wi and ci (1 ≤ wi ≤ 3, 1 ≤ ci ≤ 109) — the weight and the cost of ith souvenir.

Output
Print one number — maximum possible total cost of souvenirs that Petya can carry to the market.

Examples
Input
1 1
2 1
Output
0
Input
2 2
1 3
2 2
Output
3
Input
4 3
3 10
2 7
2 8
1 1
Output
10

题意:
给出n个物品,每个物品的重量是1或者2或者3,价值是c,请问总重量不超过m的情况下最大总价值是多少.

解法:
一个普通的01背包问题,但问题在于n和m特别地大,如果直接做肯定会TLE。不过注意到只有3种重量,所以可以排序后对1和2直接背包,3标记总量最后处理.
同样是做题,大佬们的解法就又清晰又简单,实在太强了。
大佬的代码:https://blog.csdn.net/quanqqqqq/article/details/72453155。

代码:

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<stdlib.h>
#include<cstring>
using namespace std;

struct node{long long v,s1,s2;};

long long n,m;
long long ans=0;
long long a[4+5][100000+5],b[4+5],sum[100000+5];
node dp[300000+5];

bool cmp(long long a,long long b){return a>b;}

int main()
{
    scanf("%lld%lld",&n,&m);
    for(int i=1;i<=n;i++){
        long long w,c;scanf("%lld%lld",&w,&c);
        a[w][++b[w]]=c;
    }
    for(int i=1;i<=3;i++)sort(a[i]+1,a[i]+1+b[i],cmp);
    for(int i=1;i<=b[3];i++)sum[i]=sum[i-1]+a[3][i];
    for(int i=1;i<=m;i++){
        dp[i]=dp[i-1];
        if(dp[i-1].v+a[1][dp[i-1].s1+1]>dp[i].v){
            dp[i].v=dp[i-1].v+a[1][dp[i-1].s1+1];
            dp[i].s1=dp[i-1].s1+1;
            dp[i].s2=dp[i-1].s2;
        }
        if(i>=2&&dp[i-2].v+a[2][dp[i-2].s2+1]>dp[i].v){
            dp[i].v=dp[i-2].v+a[2][dp[i-2].s2+1];
            dp[i].s1=dp[i-2].s1;
            dp[i].s2=dp[i-2].s2+1;
        }
    }
    for(int i=0;i<=b[3]&&3*i<=m;i++)ans=max(ans,dp[m-3*i].v+sum[i]);
    printf("%lld\n",ans);
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值