用c语言举例贪心算法
时间: 2023-02-18 11:38:09 浏览: 102
例如,下面的程序演示了贪心算法,它求解了一个最小化硬币组合问题:
#include <stdio.h>
// All denominations of Indian Currency
int deno[] = {1, 2, 5, 10, 20, 50, 100, 500, 1000};
int n = sizeof(deno)/sizeof(deno[0]);
void findMin(int V)
{
// Initialize result
int res[n];
// Traverse through all denomination
for (int i = n - 1; i >= 0; i--)
{
// Find denominations
while (V >= deno[i])
{
V -= deno[i];
res[i]++;
}
}
// Print result
printf("Currency Denomination : ");
for (int i = 0; i < n; i++)
if (res[i])
printf("%d = %d, ", deno[i], res[i]);
return;
}
// Driver program
int main()
{
int n = 93;
printf("Following is minimal number of change for %d: ", n);
findMin(n);
return 0;
}
结果如下:
Currency Denomination : 50 = 1, 20 = 2, 2 = 2, 1 = 1
阅读全文