USACO Section 2.1 Healthy Holsteins(状态压缩)
Burch & Kolstad
Farmer John prides himself on having the healthiest dairy cows in the world. He knows the vitamin content for one scoop of each feed type and the minimum daily vitamin requirement for the cows. Help Farmer John feed his cows so they stay healthy while minimizing the number of scoops that a cow is fed.
Given the daily requirements of each kind of vitamin that a cow needs, identify the smallest combination of scoops of feed a cow can be fed in order to meet at least the minimum vitamin requirements.
Vitamins are measured in integer units. Cows can be fed at most one scoop of any feed type. It is guaranteed that a solution exists for all contest input data.
PROGRAM NAME: holstein
INPUT FORMAT
Line 1: | integer V (1 <= V <= 25), the number of types of vitamins |
Line 2: | V integers (1 <= each one <= 1000), the minimum requirement for each of the V vitamins that a cow requires each day |
Line 3: | integer G (1 <= G <= 15), the number of types of feeds available |
Lines 4..G+3: | V integers (0 <= each one <= 1000), the amount of each vitamin that one scoop of this feed contains. The first line of these G lines describes feed #1; the second line describes feed #2; and so on. |
SAMPLE INPUT (file holstein.in)
4 100 200 300 400 3 50 50 50 50 200 300 200 300 900 150 389 399
OUTPUT FORMAT
The output is a single line of output that contains:
- the minimum number of scoops a cow must eat, followed by:
- a SORTED list (from smallest to largest) of the feed types the cow is given
If more than one set of feedtypes yield a minimum of scoops, choose the set with the smallest feedtype numbers.
SAMPLE OUTPUT (file holstein.out)
2 1 3
题意:牛需要 m 种维他命,每天牛需要每种维他命都有一个最小值,FJ有 n 种饲料,每种饲料都含有 m 种维他命,但是量不一定相同。现在 FJ 想使用最少种的维他命去饲料他的牛,如果种数相同输出字典序小的。
分析:因种数只有 15 种,对于每种饲料有选与不选两种情况,所以共有 2^15 种情况。使用状态压缩。
1 /* 2 ID: dizzy_l1 3 LANG: C++ 4 TASK: holstein 5 */ 6 #include<iostream> 7 #include<cstring> 8 #include<cstdio> 9 #include<cmath> 10 11 using namespace std; 12 13 int V[30],G[20][30],ans[20],cnt; 14 15 void search(int n,int m) 16 { 17 int t[20],s[30]; 18 int nn,a,i,j,k; 19 cnt=20; 20 nn=pow(2,n)-1; 21 for(a=1;a<=nn;a++) 22 { 23 k=0; 24 for(i=0;i<n;i++) 25 { 26 int p=pow(2,i); 27 if(a&p) 28 t[k++]=i; 29 } 30 memset(s,0,sizeof(s)); 31 for(i=0;i<k;i++) 32 { 33 for(j=0;j<m;j++) 34 { 35 s[j]+=G[t[i]][j]; 36 } 37 } 38 for(i=0;i<m;i++) 39 { 40 if(s[i]<V[i]) break; 41 } 42 if(i==m&&k-1<cnt-1) 43 { 44 for(i=0;i<k;i++) 45 ans[i]=t[i]; 46 cnt=k; 47 } 48 } 49 } 50 51 int main() 52 { 53 freopen("holstein.in","r",stdin); 54 freopen("holstein.out","w",stdout); 55 int n,m,i,j; 56 while(scanf("%d",&m)==1) 57 { 58 for(i=0;i<m;i++) 59 scanf("%d",&V[i]); 60 scanf("%d",&n); 61 for(i=0;i<n;i++) 62 for(j=0;j<m;j++) 63 scanf("%d",&G[i][j]); 64 search(n,m); 65 printf("%d ",cnt); 66 for(i=0;i<cnt-1;i++) 67 printf("%d ",ans[i]+1); 68 printf("%d\n",ans[i]+1); 69 } 70 return 0; 71 }