Topic background:
Given a series of face value change, such as 1,2,5,10,20, and then give a need to pay the money, how to use these changes to minimize the use of change of Zhang Shu?
1. Greedy
Applicable regulations: The multiple of the face value of the change meets the relationship of 2 times or more
Code:
#include <stdio.h>
#include <algorithm>
const int maxn=101;
int coins[maxn];
#define inc(i,l,r) for(int i=l;i<r;i++)
#define dec(i,r,l) for(int i=r-1;i>=l;i--)
int main(){
int count; //面值种数
scanf("%d",&count);
inc(i,0,count) scanf("%d",&coins[i]);
int X; //支付金额
scanf("%d",&X);
int ans = 0;
dec(i,count,0){
int use = X /coins[i];
ans += use;
X = X - coins[i] * use;
printf("需要面额为%d的%d张, ", coins[i], use);
printf("剩余需要支付RMB %d.\n", X);
}
printf("最少需要%d张RMB\n", ans);
return 0;
}
Test Results:
2. Dynamic programming
If our face value does not meet the condition of 2 times, such as 1, 2, 5, 7, 10;
When the payment amount = 14, the result of greed is 3 (10 + 2 + 2), and the correct result is 2 (7 + 7);
At this time, dynamic programming will be used. . .
Ideas:
1. State i can be obtained from the five states i-1, i-2, i-5, i-7, i-10, namely
dp[i]=min(dp[i]-coins[j])+1
Where amount is the total payment and count is the number of face value
2. The boundary dp [0] = 0;
Code:
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
#define inc(i,l,r) for(int i=l;i<r;i++)
int coinchange(vector<int> &coins,int amount){
vector<int> dp;
inc(i,0,amount+1) dp.push_back(-1);
dp[0]=0;
inc(i,1,amount+1)
inc(j,0,coins.size()){
if(i-coins[j]>=0&&dp[i-coins[j]]!=-1){
if(dp[i]==-1||dp[i-coins[j]]+1<dp[i])
dp[i]=dp[i-coins[j]]+1;
}
}
return dp[amount];
}
int main(){
int amount,coin,count;//支付金额,面额,钱的种类
vector<int> coins;
scanf("%d",&count);
inc(i,0,count) scanf("%d",&coin),coins.push_back(coin);
scanf("%d",&amount);
printf("%d",coinchange(coins,amount));
return 0;
}
Test Results: