Farmer John must measure Q (1 <= Q <= 20,000) quarts of his finest milk and deliver it in one big bottle to a customer. He fills that bottle with exactly the number of quarts that the customer orders.
Farmer John has always been frugal. He is at the cow hardware store where he must purchase a set of pails with which to measure out Q quarts of milk from his giant milk tank. Since the pails each cost the same amount, your task is to figure out a minimal set of pails Farmer John can purchase in order to fill a bottle with exactly Q quarts of milk. Additionally, since Farmer John has to carry the pails home, given two minimal sets of pails he should choose the "smaller" one as follows: Sort the sets in ascending order. Compare the first pail in each set and choose the set with the smallest pail. If the first pails match, compare the second pails and choose from among those, else continue until the two sets differ. Thus the set {3, 5, 7, 100} should be chosen over {3, 6, 7, 8}.
To measure out milk, FJ may completely fill a pail from the tank and pour it into the bottle. He can never remove milk from the bottle or pour milk anywhere except into the bottle. With a one-quart pail, FJ would need only one pail to create any number of quarts in a bottle. Other pail combinations are not so convenient.
Determine the optimally small number of pails to purchase, given the guarantee that at least one solution is possible for all contest input data.
Line 1: | The single integer Q |
Line 2: | A single integer P (1 <= P <= 100) which is the number of pails in the store |
Lines 3..P+2: | Each line contains a single integer pail_value (1 <= pail_value <= 10000), the number of quarts a pail holds |
16 3 3 5 7
The output is a single line of space separated integers that contains:
2 3 5
题意:让你从n个桶里选出最少的桶,使得这些桶能够搞好测出容量Q的一瓶牛奶。。。如果数量相同,按字典序
分析:这题一看就觉得是背包问题,不过仔细的分析了下,貌似是要超时的,不过暂时没想到其他法子,只好试试,结果居然很快出解了。。。不过我在输出方案是犯了个错误,导致wa了无数次,本来是贪心找这个方案的,最后发现只有全部遍历了,才保证最小- -
代码:
/* ID: 15114582 PROG: milk4 LANG: C++ */ #include<cstdio> #include<algorithm> #include<iostream> using namespace std; const int mm=22222; int a[111],f[mm],g[mm],p[mm]; int i,j,k,n,m; void dfs(int i,int j) { if(i>=f[m]) { for(i=0;i<f[m];++i) { if(p[i]<a[i])break; if(p[i]>a[i])return; } for(i=0;i<f[m];++i)a[i]=p[i]; return; } p[i]=g[j]; for(int s=j;(j=j-g[s])>=0;) if(f[j]+1==f[s])dfs(i+1,j); } int main() { freopen("milk4.in","r",stdin); freopen("milk4.out","w",stdout); while(~scanf("%d%d",&m,&n)) { for(i=0;i<n;++i) scanf("%d",&a[i]); sort(a,a+n); for(i=0;i<=m;++i)f[i]=n+1,p[i]=0; f[0]=0; for(i=n-1;i>=0;--i) for(j=m;j>=0;--j) for(k=j+a[i];k<=m;k+=a[i]) if(f[k]>f[j]+1||(f[k]==f[j]+1&&g[k]>a[i])) { f[k]=f[j]+1; g[k]=a[i]; } a[0]=m; dfs(0,m); printf("%d",f[m]); for(i=0;i<f[m];++i)printf(" %d",g[a[i]]); puts(""); } return 0; }