Links: http://hihocoder.com/problemset/problem/1038?sid=469496
Accept Code:
1#include <iostream>2#include <algorithm>3 using namespacestd;4 5 intdp[501][100001];6 intneed[501];7 intvalue[501];8 9 intMain ()Ten { One intNum,amount; ACin>>num>>amount; - for(intI=1; i<=num;i++) - { theCin>>need[i]>>Value[i]; - } - - for(intj=1; j<=num;j++) + { - for(intI=0; i<=amount;i++) + { A if(i<Need[j]) at { -dp[j][i]=dp[j-1][i]; - } - Else - { -Dp[j][i]=max (dp[j-1][i], (dp[j-1][i-need[j]]+value[j])); in } - } to } + -cout<<dp[num][amount]<<Endl; the return 0; *}
Tle Code:
1#include <iostream>2#include <algorithm>3 using namespacestd;4 5 intdp[100001][501];6 intneed[501];7 intvalue[501];8 9 intMain ()Ten { One intNum,amount; ACin>>num>>amount; - for(intI=1; i<=num;i++) - { theCin>>need[i]>>Value[i]; - } - - for(intj=1; j<=num;j++) + { - for(intI=0; i<=amount;i++) + { A if(need[j]>i) at { -dp[i][j]=dp[i][j-1]; - } - Else - { -Dp[i][j]=max (dp[i][j-1], (dp[i-need[j]][j-1]+value[j])); in } - } to } + -cout<<dp[amount][num]<<Endl; the return 0; *}
The only difference between the two pieces of code is the order in which they are defined: dp[number of items [backpack capacity]--dp[backpack capacity] [number of items].
Why is it?
[hihocoder]01 backpack Accept vs. time limit exceed code comparison