CSES - Minimizing Coins
Author: Michael Cao
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 ).
1#include <bits/stdc++.h>2using namespace std;3using ll = long long;4using vi = vector<int>;5#define pb push_back6#define rsz resize7#define all(x) begin(x), end(x)8#define sz(x) (int)(x).size()9using pi = pair<int,int>;10#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!