[题解]AT_abc231_e [ABC231E] Minimal payments

思路

首先有一个显然的贪心策略,就是先用大面值的,再用小面值的。

因为 \(n \neq 60\),先考虑搜索。

对于搜索到剩余 \(x\) 元,当前用 \(A_u\) 面值的时候。可以分为两种情况:

  1. 不找零,其答案为 a = x / a[u] + dfs(u - 1,x % a[u])
  2. 找零,其答案为 b = x / a[u] + dfs(u - 1,(x / a[u] + 1) * a[u] - x)

最终,对于此次搜索的答案为 \(\min(a,b)\)

不难发现,对于每一种状态可能为搜索多次,所以可以记忆化一下。

Code

#include <bits/stdc++.h>  
#define int long long  
#define re register  
  
using namespace std;  
  
typedef pair<int,int> pii;  
const int N = 110;  
int n,m;  
int arr[N];  
map<pii,int> mp;  
  
inline int read(){  
    int r = 0,w = 1;  
    char c = getchar();  
    while (c < '0' || c > '9'){  
        if (c == '-') w = -1;  
        c = getchar();  
    }  
    while (c >= '0' && c <= '9'){  
        r = (r << 3) + (r << 1) + (c ^ 48);  
        c = getchar();  
    }  
    return r * w;  
}  
  
inline int dfs(int u,int x){  
    if (u == 1) return x;  
    if (mp.count({u,x})) return mp[{u,x}];  
    int a = x / arr[u] + dfs(u - 1,x % arr[u]);  
    int b = x / arr[u] + dfs(u - 1,(x / arr[u] + 1) * arr[u] - x) + 1;  
    return mp[{u,x}] = min(a,b);  
}  
  
signed main(){  
    n = read();  
    m = read();  
    for (re int i = 1;i <= n;i++) arr[i] = read();  
    printf("%lld",dfs(n,m));  
    return 0;  
}  
posted @ 2024-06-22 10:51  WBIKPS  阅读(24)  评论(0)    收藏  举报