CSES - Minimizing Coins
Author: Michael Cao
Appears In
In this problem, we're asked the minimum number of coins of distinct weights needed to achieve some weight, . You can read about the solution to this classical problem in CPH Chapter 7 under "Coin Problem".
Main Idea
For this problem, we'll define as the minimum number of coins to achieve some weight, . Then, at some , we can try to use every coin. Using the -th coin represents transitioning from the state where represents the value of the -th coin. So, for , the transition is:
Finally, the base case would be , since it requires coins to get a sum of .
Warning!
Remember to initialize the array with some large value, since we are computing a minimum. Additionally, if is an int
array, don't initialize with INT_MAX
, since that could cause overflow when you add 1 for the transitions.
Warning!
Don't forget to check if , where is the large value you used, and print if so (since it's impossible to achieve a sum of ).
#include <bits/stdc++.h>using namespace std;using ll = long long;using vi = vector<int>;#define pb push_back#define rsz resize#define all(x) begin(x), end(x)#define sz(x) (int)(x).size()using pi = pair<int,int>;#define f first
Join the USACO Forum!
Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!