To solve this problem, we need to find the minimum number of coins required to make a given target amount using a set of coin denominations. This is a classic problem that can be efficiently solved using Dijkstra's Algorithm (or BFS, since each coin adds exactly one to the count of coins used). Here, we use Dijkstra's Algorithm to prioritize states with fewer coins, ensuring we find the minimal solution first.
Approach
- Problem Analysis: We need to reach the target sum using the least number of coins. Each coin can be used multiple times (unbounded knapsack variant).
- Intuition: Use a priority queue (min-heap) to always expand the state with the fewest coins first. This ensures that the first time we reach the target sum, it's with the minimal number of coins.
- Optimization: Track the minimal number of coins needed to reach each sum using a visited array. This avoids reprocessing states with higher or equal coin counts.
Solution Code
import heapq
def main():
import sys
input = sys.stdin.read().split()
ptr = 0
N = int(input[ptr])
ptr +=1
coins = list(map(int, input[ptr:ptr+N]))
ptr +=N
T = int(input[ptr])
INF = float('inf')
visited = [INF]*(T+1)
heap = []
heapq.heappush(heap, (0,0)) # (number of coins, current sum)
visited[0] = 0
while heap:
count, current = heapq.heappop(heap)
if current == T:
print(count)
return
for coin in coins:
next_sum = current + coin
if next_sum > T:
continue
if visited[next_sum] > count + 1:
visited[next_sum] = count + 1
heapq.heappush(heap, (count+1, next_sum))
print(-1) # If target can't be reached
if __name__ == "__main__":
main()
Explanation
- Initialization:
visitedarray: Stores the minimal coins needed to reach each sum (initialized to infinity, except sum 0 which uses 0 coins).- Priority queue: Starts with the state (0 coins, sum=0).
- Processing:
- Pop the state with the fewest coins from the heap.
- If the current sum equals the target, return the count of coins (since it's the minimal).
- For each coin, compute the new sum. If the new sum is within the target and the new coin count is better (fewer) than the existing value in
visited, updatevisitedand push the new state to the heap.
- Result: If the heap is exhausted without reaching the target, return -1 (target can't be formed with given coins).
This approach efficiently finds the minimal coins using Dijkstra's Algorithm, ensuring optimal performance even for larger target values. The time complexity is O(T * log T) (due to heap operations), which is feasible for most practical cases. For even better performance (O(T)), BFS can be used since each step adds exactly one coin (level order traversal gives minimal coins first). However, the given solution is correct and works well for the problem.


(免责声明:本文为本网站出于传播商业信息之目的进行转载发布,不代表本网站的观点及立场。本文所涉文、图、音视频等资料的一切权利和法律责任归材料提供方所有和承担。本网站对此资讯文字、图片等所有信息的真实性不作任何保证或承诺,亦不构成任何购买、投资等建议,据此操作者风险自担。) 本文为转载内容,授权事宜请联系原著作权人,如有侵权,请联系本网进行删除。