标签:cow else namespace efi different title 复杂 容量 tor
# include <stdio.h> # include <string.h> # include <stdlib.h> # include <iostream> # include <fstream> # include <vector> # include <queue> # include <stack> # include <map> # include <math.h> # include <algorithm> using namespace std; # define pi acos(-1.0) # define mem(a,b) memset(a,b,sizeof(a)) # define FOR(i,a,n) for(int i=a; i<=n; ++i) # define For(i,n,a) for(int i=n; i>=a; --i) # define FO(i,a,n) for(int i=a; i<n; ++i) # define Fo(i,n,a) for(int i=n; i>a ;--i) typedef long long LL; typedef unsigned long long ULL; int a[1000+5],b[1000+5],dp[1000+5][1000+5]; int main() { int t,n,v; cin>>t; while(t--) { cin>>n>>v; FOR(i,1,n)cin>>b[i]; FOR(i,1,n)cin>>a[i]; mem(dp,0); FOR(i,1,n)FOR(j,0,v) { if(a[i]<=j)dp[i][j]=max(dp[i-1][j],dp[i-1][j-a[i]]+b[i]); else dp[i][j]=dp[i-1][j]; } cout<<dp[n][v]<<endl; } return 0; }
解法二:时间复杂度O(n2),空间复杂度O(n)
# include <stdio.h> # include <string.h> # include <stdlib.h> # include <iostream> # include <fstream> # include <vector> # include <queue> # include <stack> # include <map> # include <math.h> # include <algorithm> using namespace std; # define pi acos(-1.0) # define mem(a,b) memset(a,b,sizeof(a)) # define FOR(i,a,n) for(int i=a; i<=n; ++i) # define For(i,n,a) for(int i=n; i>=a; --i) # define FO(i,a,n) for(int i=a; i<n; ++i) # define Fo(i,n,a) for(int i=n; i>a ;--i) typedef long long LL; typedef unsigned long long ULL; int a[1000+5],b[1000+5],dp[1000+5]; int main() { int t,n,v; cin>>t; while(t--) { int ans=0; cin>>n>>v; FOR(i,1,n)cin>>b[i]; FOR(i,1,n)cin>>a[i]; mem(dp,0); FOR(i,1,n)For(j,v,0) { if(a[i]<=j)dp[j]=max(dp[j],dp[j-a[i]]+b[i]); } cout<<dp[v]<<endl; } return 0; }
HDU 2602 Bone Collector (01背包问题)
标签:cow else namespace efi different title 复杂 容量 tor
原文地址:http://www.cnblogs.com/teble/p/7191330.html