( ⊙ o ⊙ ) 题目:
(⊙v⊙),代码:
1.dfs
//会超时!!!! #include<iostream> #include<cstdio> using namespace std; int n,t,ans; int w[1003],v[1003]; void dfs(int x,int val,int left) { if(x == n+1){ ans = max(ans,val); return ; } dfs(x+1,val,left); if(left >= w[x]) dfs(x+1,val + v[x],left - w[x]); } int main() { cin>>n>>t; for(int i=1; i<=n; i++) cin>>w[i]>>v[i]; dfs(1,0,t); cout<<ans<<endl; return 0; }
2.dp
#include<iostream> #include<cstdio> using namespace std; int n,V; int val[1333],wight[1333],f[1333]; int main() { cin>>V>>n; for(int i=1; i<=n; i++) { cin>>wight[i]>>val[i]; } for(int i=1; i<=n; i++) { for(int j=V; j>=0; j--) { if(j >= wight[i]) f[j] = max(f[j],f[j-wight[i]]+val[i]); } } cout<<f[V]<<endl; return 0; }
多重背包的二进制优化:
1 #include<iostream> 2 #include<cstdio> 3 using namespace std; 4 5 const int N = 1333333; 6 int wight,val,numb,v[N],w[N]; 7 int n,m,f[N],nl; 8 9 int main() { 10 cin>>n>>m; 11 for(int i=1; i<=n; i++) { 12 int t = 1; 13 cin>>wight>>val>>numb; 14 while(numb >= t) { 15 w[++nl] = wight * t; 16 v[nl] = val * t; 17 numb-=t; 18 t*=2; 19 } 20 w[++nl] = wight * numb; 21 v[nl] = val * numb; 22 } 23 for(int i=1; i<=nl; i++) 24 for(int j=m; j>=w[i]; j--) 25 f[j] = max(f[j],f[j-w[i]]+v[i]); 26 cout<<f[m]<<endl; 27 return 0; 28 }
如果数据过大,还是会超时,就可以用单调队列优化。