首頁  >  文章  >  後端開發  >  C++程式:計算使用硬幣支付達到n所需的操作次數

C++程式:計算使用硬幣支付達到n所需的操作次數

WBOY
WBOY轉載
2023-09-14 20:53:041132瀏覽

C++程式:計算使用硬幣支付達到n所需的操作次數

假設我們有五個數字,N,A,B,C,D。我們從數字0開始,結束於N。我們可以透過一定數量的硬幣來改變一個數字,具體操作如下:

  • 將數字乘以2,支付A個硬幣
  • 將數字乘以3,支付B個硬幣
  • 將數字乘以5,支付C個硬幣
  • 增加或減少數字1,支付D個硬幣

我們可以任意次數以任意順序執行這些操作。我們需要找到達到N所需的最少硬幣數量

因此,如果輸入是N = 11; A = 1; B = 2; C = 2; D = 8,那麼輸出將是19,因為最初x為0。

用8個硬幣將x增加1(x=1)。

用1個硬幣將x乘以2(x=2)。

用2個硬幣將x乘以5(x=10)。

用8個硬幣增加1(x=11)。

步驟

為了解決這個問題,我們將按照以下步驟進行:

Define one map f for integer type key and value
Define one map vis for integer type key and Boolean type value
Define a function calc, this will take n
if n is zero, then:
   return 0
if n is in vis, then:
   return f[n]
vis[n] := 1
res := calc(n / 2) + n mod 2 * d + a
if n mod 2 is non-zero, then:
   res := minimum of res and calc((n / 2 + 1) + (2 - n mod 2)) * d + a)
res := minimum of res and calc(n / 3) + n mod 3 * d + b
if n mod 3 is non-zero, then:
   res := minimum of res and calc((n / 3 + 1) + (3 - n mod 3)) * d + b)
res := minimum of res and calc(n / 5) + n mod 5 * d + c
if n mod 5 is non-zero, then:
   res := minimum of res and calc((n / 5 + 1) + (5 - n mod 5))
if (res - 1) / n + 1 > d, then:
   res := n * d
return f[n] = res
From the main method, set a, b, c and d, and call calc(n)

Example

讓我們來看下面的實作以更好地理解−

#include <bits/stdc++.h>
using namespace std;

int a, b, c, d;
map<long, long> f;
map<long, bool> vis;

long calc(long n){
   if (!n)
      return 0;
   if (vis.find(n) != vis.end())
      return f[n];
   vis[n] = 1;
   long res = calc(n / 2) + n % 2 * d + a;
   if (n % 2)
      res = min(res, calc(n / 2 + 1) + (2 - n % 2) * d + a);
   res = min(res, calc(n / 3) + n % 3 * d + b);
   if (n % 3)
      res = min(res, calc(n / 3 + 1) + (3 - n % 3) * d + b);
   res = min(res, calc(n / 5) + n % 5 * d + c);
   if (n % 5)
      res = min(res, calc(n / 5 + 1) + (5 - n % 5) * d + c);
   if ((res - 1) / n + 1 > d)
      res = n * d;
   return f[n] = res;
}
int solve(int N, int A, int B, int C, int D){
   a = A;
   b = B;
   c = C;
   d = D;
   return calc(N);
}
int main(){
   int N = 11;
   int A = 1;
   int B = 2;
   int C = 2;
   int D = 8;
   cout << solve(N, A, B, C, D) << endl;
}

輸入

11, 1, 2, 2, 8

輸出

19

以上是C++程式:計算使用硬幣支付達到n所需的操作次數的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除