Input
多组数据。对于每组数据:
第一行为正整数n,表示菜的数量。n<=1000。
第二行包括n个正整数,表示每种菜的价格。价格不超过50。
第三行包括一个正整数m,表示卡上的余额。m<=1000。
n=0表示数据结束。
Output
对于每组输入,输出一行,包含一个整数,表示卡上可能的最小余额。
Sample Input
1
50
5
10
1 2 3 2 1 1 2 3 2 1
50
0
Sample Output
-45
32
#include <cstdio> #include <algorithm> #include <iostream> #include <cstring> using namespace std; const int maxn = 1010; const int inf = 0x3f3f3f3f; int n; int m; int f[maxn]; int c[maxn]; int w[maxn]; int main() { int t; while(scanf("%d",&n)&&n) { for(int i=1;i<=n;++i)cin>>w[i]; cin>>m; sort(w+1,w+1+n); int mm=0; memset(c,0,sizeof c); c[0]=1; for(int i=1;i<=n;++i) for(int j=m-5;j>=0;--j) if(c[j]) { c[j+w[i]]=1; mm=max(mm,j+w[i]); } cout<<m-mm<<endl; } return 0; }
依旧是运用了01背包的做法,但是还加入了排序,为了使自己买的更多,要先将小的买下来
原文:https://www.cnblogs.com/-113/p/12319247.html