一 .题目描述
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
二.题目分析
本题简单来看就是一个搜索过程,从1开始搜索,可以选取BFS和DFS搜索策略,由于BFS中需要用到栈,还是果断选用了DFS,所搜的最大深度是G,注意在搜索路径中保存最优解即可。
三.代码
#include <stdio.h>
#include <stdlib.h>
int V,G,need[25],feed[1000][25];
int min=1001,ans[1000],sum[25],te[1000];
int check(int *sum)
{
int i;
for(i=0;i<V;i++)
{
if(sum[i]<need[i])
return 0;
}
return 1;
}
void DFS(int k,int n)
{
int i;
if(k==G) //最大的深度是G
return ;
for(i=0;i<V;i++)
sum[i]+=feed[k][i];
te[n]=k;
if(check(sum))//如果符合条件,则找到一个解,更新最优解
{
if(min>n)
{
min=n;
for(i=0;i<=n;i++)
ans[i]=te[i];
}
}
else //否则,继续向深一步搜索
DFS(k+1,n+1);
// 注意此处的回溯过程...
for(i=0;i<V;i++)
sum[i] -=feed[k][i];
DFS(k+1,n); //搜索同一深度的其他方案
}
int main()
{
int i,j,k;
FILE *in=fopen("holstein.in","r"),*out=fopen("holstein.out","w");
if(!in||!out)
{
printf("file open error!\n");
return -1;
}
fscanf(in,"%d",&V);
for(i=0;i<V;i++)
fscanf(in,"%d",&need[i]);
fscanf(in,"%d",&G);
for(i=0;i<G;i++)
for(j=0;j<V;j++)
fscanf(in,"%d",&feed[i][j]);
for(i=0;i<1000;i++)
ans[i]=0;
DFS(0,0); //从0号配料开始搜索,深度开始为0
fprintf(out,"%d ",min+1);
for(i=0;i<min;i++)
fprintf(out,"%d ",ans[i]+1);
fprintf(out,"%d\n",ans[i]+1);
return 0;
}