标签:can ref pid string || sum pair set algorithm
二进制优化多重背包
将硬币的价值看做费用,使用的硬币个数看做价值,将第\(i\)种硬币看成\(c_i\)个价值为\(a_i\)的硬币跑01背包的话时间是\(O(m\sum c)\)的,显然不大行
注意到可以对\(c_i\)直接进行二进制拆分,把它拆成\(log\)个物品(\(2^0,2^1,\cdots,2^k,c_i-2^k(2^{k+1}>c_i)\)),再跑01背包时间就是\(O(m\sum log\ c_i)\)的,可以接受
#include<iostream>
#include<string.h>
#include<string>
#include<stdio.h>
#include<algorithm>
#include<vector>
#include<math.h>
#include<queue>
#include<set>
#include<map>
using namespace std;
typedef long long ll;
typedef long double db;
const int N=10000;
const db pi=acos(-1.0);
#define lowbit(x) (x)&(-x)
#define sqr(x) (x)*(x)
#define rep(i,a,b) for (register int i=a;i<=b;i++)
#define per(i,a,b) for (register int i=a;i>=b;i--)
#define fir first
#define sec second
#define mp(a,b) make_pair(a,b)
#define pb(a) push_back(a)
#define maxd 998244353
#define eps 1e-8
int n,m,w[10100],c[10100],val[10100],dp[101000],tot=0;
int read()
{
int x=0,f=1;char ch=getchar();
while ((ch<'0') || (ch>'9')) {if (ch=='-') f=-1;ch=getchar();}
while ((ch>='0') && (ch<='9')) {x=x*10+(ch-'0');ch=getchar();}
return x*f;
}
int main()
{
while ((scanf("%d%d",&n,&m)) && (n) && (m))
{
rep(i,1,n) val[i]=read();tot=0;
rep(i,1,n)
{
int W=read(),tmp=0;
while (W>=(1<<tmp))
{
w[++tot]=(1<<tmp)*val[i];c[tot]=1;
W-=(1<<tmp);tmp++;
}
if (W) {w[++tot]=W*val[i];c[tot]=1;}
}
rep(i,1,m) dp[i]=-maxd;
rep(i,1,tot)
per(j,m,w[i])
dp[j]=max(dp[j],dp[j-w[i]]+c[i]);
int ans=0;
rep(i,1,m) ans+=(dp[i]>0);
printf("%d\n",ans);
}
return 0;
}
标签:can ref pid string || sum pair set algorithm
原文地址:https://www.cnblogs.com/encodetalker/p/11247763.html