Consider a money system consisting of coins. Each coin has a positive integer value. Your task is to produce a sum of money using the available coins in such a way that the number of coins is minimal.
For example, if the coins are and the desired sum is , an optimal solution is which requires coins.
Input
The first input line has two integers and : the number of coins and the desired sum of money.
The second line has distinct integers : the value of each coin.
Output
Print one integer: the minimum number of coins. If it is not possible to produce the desired sum, print .
Constraints
Example
Input:3 11
1 5 7
Output:3
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <bits/stdc++.h> | |
using namespace std; | |
int main() { | |
int n, target; | |
cin >> n >> target; | |
vector<int> c(n); | |
for (int& v : c) cin >> v; | |
vector<int> dp(target + 1, 1e9); | |
dp[0] = 0; | |
for (int i = 1; i <= target; i++) { | |
for (int j = 0; j < n; j++) { | |
if (i - c[j] >= 0) { | |
dp[i] = min(dp[i], dp[i - c[j]] + 1); | |
} | |
} | |
} | |
cout << (dp[target] == 1e9 ? -1 : dp[target]) << endl; | |
} |
No comments:
Post a Comment