记fij为考虑到 2^i 时 剩余为 j*2^i
然后层内转移 这层剩下的翻倍给下一层用
详见一道加强版:http://blog.csdn.net/u014609452/article/details/53157847
#include<cstdio>
#include<cstdlib>
#include<algorithm>
#include<cstring>
#define cl(x) memset(x,0,sizeof(x))
using namespace std;
typedef pair<int,int> abcd;
typedef long long ll;
inline char nc(){
static char buf[100000],*p1=buf,*p2=buf;
if (p1==p2) { p2=(p1=buf)+fread(buf,1,100000,stdin); if (p1==p2) return EOF; }
return *p1++;
}
inline void read(int &x){
char c=nc(),b=1;
for (;!(c>='0' && c<='9');c=nc()) if (c=='-') b=-1;
for (x=0;c>='0' && c<='9';x=x*10+c-'0',c=nc()); x*=b;
}
int n,W,m;
int w[32];
ll f[34][2005];
abcd lst[33][105];int cnt[33];
int main(){
freopen("t.in","r",stdin);
freopen("t.out","w",stdout);
while (1){
read(n); read(W); m=0;
for (int i=0;i<=30;i++){
w[i]=W&1,W>>=1;
if (w[i]) m=max(m,i);
}
if (n==-1 && W==-1) break;
for (int i=1;i<=n;i++){
int a,b=0,tem,val;
read(tem); read(val);
while (tem%2==0 && tem/2>10)
b++,tem>>=1;
a=tem;
lst[b][++cnt[b]]=abcd(a,val);
}
ll Ans=0;
memset(f,-0x3f,sizeof(f));
for (int i=m;~i;i--){
f[i][w[i]]=max(f[i][w[i]],0LL);
for (int j=1;j<=cnt[i];j++)
for (int k=lst[i][j].first;k<=2000;k++)
f[i][k-lst[i][j].first]=max(f[i][k-lst[i][j].first],f[i][k]+lst[i][j].second);
if (i){
for (int k=0;k<=2000;k++)
f[i-1][min(2000,k*2+w[i-1])]=max(f[i-1][min(2000,k*2+w[i-1])],f[i][k]);
}else{
for (int k=0;k<=2000;k++)
Ans=max(Ans,f[i][k]);
}
}
printf("%lld\n",Ans);
cl(lst); cl(f); cl(cnt);
}
return 0;
}