据说是清华07年的研究生复试机试题,类似01背包,动态规划一直不太会,这道题不难,刚好可以练练手。
题目描述:
有若干张邮票,要求从中选取最少的邮票张数凑成一个给定的总值。
如,有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
代码:
#include <iostream>
using namespace std;
//N < 20
//M <100
//dp[i,j]=min(dp[i-1,j-var[i]]+1,dp[i-1,j]);
#define INFINITY 999
int var[1001];
int dp[1001][1001];
int N;
int M;
int main()
{
while(cin>>M>>N)
{
for(int i = 1;i <= N; i++)
{
cin >> var[i];
}
for(int i = 1;i<=M;i++)
{
dp[0][i]=INFINITY;
}
for(int i= 0;i<=N;i++)
{
dp[i][0]=0;
}
int j;
int i;
for(i=1;i<=N;i++)
{
for(j=1;j<=M;j++)
{
if(j>=var[i])
{
dp[i][j]=min(dp[i-1][j-var[i]]+1,dp[i-1][j]);
}
else
dp[i][j]=dp[i-1][j];
}
}
if(dp[N][M] != INFINITY)
cout<<dp[N][M]<<endl;
else
cout<<"0"<<endl;
}
return 0;
}