CF 808E. Selling Souvenirs

来源:互联网 发布:营销qq加好友软件 编辑:程序博客网 时间:2024/05/21 18:35

E. Selling Souvenirs
time limit per test2 seconds
memory limit per test256 megabytes
inputstandard input
outputstandard output
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

不错的dp题。一看题目就想到直接简单贪心,后来一想不对,是个dp题,由于我的做法本质和官方题解是一样的,下面就说官方题解吧(自己的太丑。。)
我们用dp[i]表示一个三元集,分别是费用是i时只用费用为1和2的物品可以得到的最大价值,费用1的物品所用的个数和费用2的物品所用的个数。
dp[i]可以由dp[i-1]与dp[i-2]得出。然后枚举费用为3的物品的个数k,然后剩下的就是dp[m-3*k],这样for一边就出来了。详细的见下面的代码

代码:

#include<bits/stdc++.h>using namespace std;typedef long long ll;int cmp(int x,int y){    return x>y;}struct node{    ll val;    ll x1,x2;}dp[300005];int n,w,c,m;int num[4];ll a[4][100005],cun[4][100005];int main(){    cin>>n>>m;    memset(a,0,sizeof(a));    memset(num,0,sizeof(num));    memset(cun,0,sizeof(cun));    for(int i=0;i<n;i++)    {        scanf("%d%d",&w,&c);        a[w][++num[w]]=c;    }    for(int i=1;i<=3;i++)    {        sort(a[i]+1,a[i]+1+num[i],cmp);        for(int j=1;j<=num[i];j++)            cun[i][j]=a[i][j]+cun[i][j-1];//每次肯定选用价值最大物品所以这里排了下序,求了下前缀和     }    dp[0].val=dp[0].x1=dp[0].x2=0;    for(int i=1;i<=m;i++)    {        dp[i]=dp[i-1];        if(dp[i-1].val+a[1][dp[i-1].x1+1]>dp[i].val)         {            dp[i].val=dp[i-1].val+a[1][dp[i-1].x1+1];            dp[i].x1=dp[i-1].x1+1;            dp[i].x2=dp[i-1].x2;        }        if(i>=2&&dp[i-2].val+a[2][dp[i-2].x2+1]>dp[i].val)        {            dp[i].val=dp[i-2].val+a[2][dp[i-2].x2+1];            dp[i].x1=dp[i-2].x1;            dp[i].x2=dp[i-2].x2+1;        }    }    ll ans=0;    for(int i=0;i<=num[3];i++)    {        if(i*3<=m)        {            ans=max(ans,dp[m-i*3].val+cun[3][i]);        }        else break;    }    //cout<<dp[m-6].val+cun[3][2]<<endl;    cout<<ans<<endl;    return 0;}
原创粉丝点击