http://acm.hdu.edu.cn/showproblem.php?pid=1114
在0/1背包中有说,当只有f[0]=0,其他值为-∞时,可以求到恰好是装满时的最大值.
这题应用这个原理,即只有f[0]=0,其他的都不为0,应该讲它设置为+∞,则恰好可以求到装满时的最小指.
View Code
1 #include <iostream> 2 #define maxn 10005 3 #define M 505 4 using namespace std; 5 int ans[maxn], v[M], w[M]; 6 int main() 7 { 8 int t, n, m, i, j, a; 9 cin >> t; 10 while(t--) 11 { 12 cin >> a >> m; 13 m -= a; 14 cin >> n; 15 for(i = 0; i < n; i++) 16 cin >> w[i] >> v[i]; 17 for(i = 0; i <= m; i++) 18 ans[i] = 0x7fffffff; 19 ans[0] = 0; 20 for(i = 0; i < n; i++) 21 for(j = v[i]; j <= m; j++) 22 { 23 if( ans[j-v[i]]+w[i] < ans[j] && ans[j-v[i]] != 0x7fffffff) 24 ans[j] = ans[j-v[i]]+w[i]; 25 } 26 if(ans[m] == 0x7fffffff) cout << "This is impossible." << endl; 27 else cout << "The minimum amount of money in the piggy-bank is " << ans[m] << "." << endl; 28 } 29 return 0; 30 }