题目形貌:给定面值为1元、5元、10元、20元、50元的硬币,和一个需要找零的金额,要求利用最少的硬币数量找零。 贪心策略:总是优先选择面值最大的硬币进行找零。 算法实现(Pascal语言):
```pascal program ChangeMaking;
var coins: array[1..5] of integer = (50, 20, 10, 5, 1); amount, i, count: integer;
begin writeln('请输入需要找零的金额:'); readln(amount); count := 0;
for i := 1 to 5 do
begin
while amount >= coins[i] do
begin
amount := amount - coins[i];
count := count + 1;
end;
end;
writeln('使用的最少硬币数量:', count);
复制代码
end. ```
2. 背包题目(0-1背包)
题目形貌:给定肯定重量限定的背包,和多少可选物品,每个物品有特定的重量和代价,求能放入背包的最大代价。 贪心策略:根据代价与重量的比率(代价密度)进行排序,并尽可能选择代价密度高的物品。 算法实现(Pascal语言):
```pascal type Item = record weight, value: integer; density: real; end;
var items: array[1..100] of Item; capacity, i, n: integer; totalValue: real;
procedure SortItems(n: integer); var i, j: integer; temp: Item; begin for i := 1 to n - 1 do for j := 1 to n - i do if items[j].density < items[j + 1].density then begin temp := items[j]; items[j] := items[j + 1]; items[j + 1] := temp; end; end;
begin writeln('请输入物品数量和背包容量:'); readln(n, capacity); writeln('请输入每个物品的重量和代价:');