题目1209:最小邮票数
时间限制:1 秒
内存限制:32 兆
特殊判题:否
提交:1669
解决:551
题目描述:
有若干张邮票,要求从中选取最少的邮票张数凑成一个给定的总值。
如,有1分,3分,3分,3分,4分五张邮票,要求凑成10分,则使用3张邮票:3分、3分、4分即可。
输入:
有多组数据,对于每组数据,首先是要求凑成的邮票总值M,M<100。然后是一个数N,N〈20,表示有N张邮票。接下来是N个正整数,分别表示这N张邮票的面值,且以升序排列。
输出:
对于每组数据,能够凑成总值M的最少邮票张数。若无解,输出0。
样例输入:
10
5
1 3 3 3 4
样例输出:
3
来源:
2007年清华大学计算机研究生机试真题
//动态规划,类似背包
#include<stdio.h>
#include<string.h>
int min(int a,int b)
{return a<b?a:b;}
int a[1000],dp[1000];
#define inf 1000000
int main()
{
int i,j,n,m,sum,x,que;
while(scanf("%d%d",&n,&m)!=EOF)
{
memset(dp,inf,sizeof(dp));
for(i=0;i<m;i++)
scanf("%d",&a[i]);
dp[0]=0;
for(i=0;i<m;i++)
for(j=n;j>=0;j--)
if(j-a[i]>=0)
dp[j]=min(dp[j-a[i]]+1,dp[j]);
if(dp[n]>20)
printf("0\n");
else
printf("%d\n",dp[n]);
}
return 0;
}