01背包 Educational Codeforces Round 21 E. Selling Souvenirs

传送门


E. Selling Souvenirs
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard 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 ≤ 1000001 ≤ 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 ≤ 31 ≤ 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个数据 总重m 在不超过总重的情况下,在下面n个数据里选价值c加起来最大的背包,输出最终的最大价值。



#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N=300010,M=300010;
int n,m,i,j,k,w,x,y,o,q[N];ll f[N],g[N],v[M];
struct P{int x,y;}a[M];//x 重量  y  价值
bool cmp(P a,P b){return a.x==b.x?a.y>b.y:a.x<b.x;}
void solve(int l,int r,int dl,int dr)
{
  int m=(l+r)>>1,dm=dl;ll&d=g[m];d=0;//g[m]=d dm为初始dl d取最小值
  for(int i=dl;i<=dr&&i<=m;i++)
  {//从dl到dr
    ll t=f[q[i]];
    if(m-i<=o)t+=v[m-i];//如果有的话就把v中 也就是最大价值最小重量的几个
    //东西加起来  如果v[m-i] 没有的话就是0
    if(t>d)d=t,dm=i;//更新d--能达到的最大值
  }
  if(l<m)solve(l,m-1,dl,dm);
  if(r>m)solve(m+1,r,dm,dr);
}
int main()
{
  scanf("%d%d",&n,&m);
  for(i=1;i<=n;i++)scanf("%d%d",&a[i].x,&a[i].y);
  sort(a+1,a+n+1,cmp);//排序
  for(i=1;i<=n;i=j)
  {
    w=a[i].x;//w取最前的价值
    if(w>m)break;//剪枝
    for(j=i;j<=n&&a[i].x==a[j].x;j++)v[j-i+1]=v[j-i]+a[j].y;//相同的重量且同价值的处理
    o=j-i;//数组v 有多少个相同的(o)
    for(k=0;k<w;k++)
    {
      for(x=k,y=0;x<=m;x+=w)q[++y]=x;//能取多少个(y个)w存在q里
      solve(1,y,1,y);
      for(x=1;x<=y;x++)f[q[x]]=g[x];//更新f[]值
    }
  }
  printf("%I64d",f[m]);
}


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值