2016年8月10日 星期三

找零使用最少硬幣(CPP版參考解)

輸入第一列 t 代表有 t 組資料,每組2列:第1列  n 種 ,  m元,第2列 n 種的面額

範例輸入:
3
5 50
1 3 5 7 13
5 50
1 5 6 7 15
8 125
1 2 3 10 11 12 20 21
範例輸出
6
4
6
參考程式碼:
#include <iostream>
#include <algorithm>
using namespace std;
const int MaxN = 20;
const int MaxM = 50000;
const int INF = MaxM+1;
int a[MaxN];
int d[MaxM+1];
int n,m;

int dp(int r)
{
   int i,v , u = INF, j=n;
   if(d[r]<INF) return d[r];  // 已有值
   for(i=n-1; i>=0; --i)
   {
if(r>a[i])
{
   v = 1 + dp(r-a[i]); // 金額 r = a[i] + 剩下的金額
   if(v < u)   u=v;
}
   }
   d[r] = u;
   return u;
}

int main(void)
{
   int i,j,k,t;
   cin >> t; // t組資料
   while( t-- )
   {
      cin >> n >> m;  //每組兩列,第1列 n種硬幣, 要換 m 元
      for(i=0; i<n; ++i) cin >> a[i];
      sort(a,a+n) ; //有需要可能需排序
// 設定初值,1個
      for(i=0; i<=m; ++i) d[i] = INF;  // fill
      for(i=0;i<n;++i)  d[a[i]] = 1; // 硬幣面值的數額只需換1個
      int ans =  dp(m);
      cout << ans << endl;
   }
   return 0;

}

Related Posts:

  • APCS 105年3月題2-矩陣轉換(C++參考)APCS Y16M3-Q2 -矩陣轉換  問題描述 輸入格式:原題單測資,本參考改為多測資,讀至EOF, 每筆測資說明如下:第一行有三個介於 1 與 10 之間的正整數  R, C, M 。 接下來有  R  行(line)是矩陣 B 的內… Read More
  • To P2 之 a010質因數分解參考程式碼 ,最後有另一組建質數表的 genp程式 // a010 #include <iostream> #include <cstring> #include <vector> #include <cmath> #define maxn 46340… Read More
  • APCS 105年3月題1-成績指標(C++參考)APCS Y16M3-Q1 成績指標  問題描述   一次考試中,於所有及格學生中獲取最低分數者最為幸運,反之,於所有不及格同學中,獲取最高分數者,可以說是最為不幸,而此二種分數,可以視為成績指標。   請你設計一支程式,讀入全班成績(人數不固定),請對所有分數進行排序,並分別找出不及格中… Read More
  • Z3A、P3A 9/17 進度Z3A 請將9/4的題目練會,另題單未測部份 9/17要測一下 P3A 9/17要講及練  104 考古題, 另明後天會公布 APCS四題的參考解… Read More
  • 104M-P11 質因數分解(CPP版參考)參考程式碼1 #include <iostream> #include <cstring> // memset #include <vector> // vector #include <cmath>  // sqrt /* size(25… Read More

0 意見:

張貼留言