题目
洛谷P2851.The Fewest Coins G
题目描述
Farmer John has gone to town to buy some farm supplies. Being a very efficient man, he always pays for his goods in such a way that the smallest number of coins changes hands, i.e., the number of coins he uses to pay plus the number of coins he receives in change is minimized. Help him to determine what this minimum number is.
FJ wants to buy T (1 ≤ T ≤ 10,000) cents of supplies. The currency system has N (1 ≤ N ≤ 100) different coins, with values V1, V2, …, VN (1 ≤ Vi ≤ 120). Farmer John is carrying C1 coins of value V1, C2 coins of value V2, ...., and CN coins of value VN (0 ≤ Ci ≤ 10,000). The shopkeeper has an unlimited supply of all the coins, and always makes change in the most efficient manner (although Farmer John must be sure to pay in a way that makes it possible to make the correct change).
农夫John想到镇上买些补给。为了高效地完成任务,他想使硬币的转手次数最少。即使他交付的硬 币数与找零得到的的硬币数最少。
John想要买价值为T的东西。有N(1<=n<=100)种货币参与流通,面值分别为V1,V2..Vn (1<=Vi<=120)。John有Ci个面值为Vi的硬币(0<=Ci<=10000)。
我们假设店主有无限多的硬币, 并总按最优方案找零。注意无解输出-1。
输入格式
Line 1: Two space-separated integers: N and T.
Line 2: N space-separated integers, respectively V1, V2, ..., VN coins (V1, ...VN)
Line 3: N space-separated integers, respectively C1, C2, ..., CN
输出格式
Line 1: A line containing a single integer, the minimum number of coins involved in a payment and change-making. If it is impossible for Farmer John to pay and receive exact change, output -1.
输入样例
3 70
5 25 50
5 2 1
输出样例
3
C++ 代码
#include<bits/stdc++.h>
using namespace std;
int f[20010],g[20010];
//f[i]、g[i]分别表示John和店长付i元钱最少需要用的硬币
int v[110],c[110];//如题意所示
int main(){
int n,t;
scanf("%d %d",&n,&t);
for(int i=1;i<=n;i++){
scanf("%d",&v[i]);//输入每个钱币的面值
}
int sum=0,mx=10000;
for(int i=1;i<=n;i++){//输入每个钱币的钱总量
scanf("%d",&c[i]);
sum+=c[i]*v[i];//求农夫拥有的钱总量
//mx=max(mx,v[i]*v[i]);
}
if(sum<t){//买不起,退了
printf("-1\n");
return 0;
}
memset(g,0x3f,sizeof(g));
memset(f,0x3f,sizeof(f));
g[0]=0;
f[0]=0;
for(int i=1;i<=n;i++){
for(int j=v[i];j<=mx;j++){//Rob找j元钱所用的最小钱数
g[j]=min(g[j],g[j-v[i]]+1);
}
}
//实际上应该是g[i][j]=min(g[i-1][j],g[i][j-v[i]+1])
//g[i][j]表示考虑到第i个物品支付j元的最少硬币数
//但是因为第一维存储的信息用不到
//且更新前g[i][j]记录的就是g[i-1][j]的信息
//所以可以只用一维
for(int i=1;i<=n;i++){
for(int j=1;j<=c[i];j<<=1){//二进制拆分的思想
for(int k=t+mx;k>=j*v[i];k--){
//倒过来更新(实际上是拆分成01背包的形式)
f[k]=min(f[k],f[k-j*v[i]]+j);
}
c[i]-=j;//相当于用拆分的物品进行了一次更新,要从数量中减去
}
if(c[i]){//还有剩余的
for(int k=t+mx;k>=c[i]*v[i];k--){
f[k]=min(f[k],f[k-c[i]*v[i]]+c[i]);
}
}
}
int ans=0x3f3f3f3f;
for(int i=t;i<=t+mx;i++){
ans=min(ans,f[i]+g[i-t]);
}
printf("%d\n",ans==0x3f3f3f3f?-1:ans);
return 0;
}
一个萌新,请多多关照