由于数组的滚动过程中当前值(i,j)的更新需要用到上一层的(i-1,j-wi)的值,所以在更新当前的j之前不能更新上一层的j之前的值,故01背包是从后向前更新的(重量取值是从大到小的)。
代码如下:
1 #include<bits/stdc++.h> 2 using namespace std; 3 typedef unsigned int ui; 4 typedef long long ll; 5 typedef unsigned long long ull; 6 #define pf printf 7 #define mem(a,b) memset(a,b,sizeof(a)) 8 #define prime1 1e9+7 9 #define prime2 1e9+9 10 #define pi 3.14159265 11 #define lson l,mid,rt<<1 12 #define rson mid+1,r,rt<<1|1 13 #define scand(x) scanf("%llf",&x) 14 #define f(i,a,b) for(int i=a;i<=b;i++) 15 #define fm(i,a,b) for(int i=a;i>=b;i--) 16 #define scan(a) scanf("%d",&a) 17 #define dbg(args) cout<<#args<<":"<<args<<endl; 18 #define pb(i) push_back(i) 19 #define ppb(x) pop_back(x) 20 #define inf 0x3f3f3f3f 21 #define maxn 100005 22 int n,m,t,vol; 23 int w[maxn],v[maxn],dp[maxn]; 24 int main() 25 { 26 //freopen("input.txt","r",stdin); 27 //freopen("output.txt","w",stdout); 28 std::ios::sync_with_stdio(false); 29 scan(t); 30 while(t--) 31 { 32 scan(n);scan(vol); 33 f(i,1,n) 34 scan(v[i]); 35 f(i,1,n)scan(w[i]); 36 mem(dp,0); 37 for(int i=1;i<=n;i++) 38 for(int j=vol;j>=w[i];j--) 39 { 40 dp[j]=max(dp[j],dp[j-w[i]]+v[i]); 41 } 42 pf("%d ",dp[vol]); 43 } 44 }