fork download
  1. <?php
  2. // Staring straight up into the sky ... oh my my
  3.  
  4. function calculateDelivery(&$banknotes, $amount){
  5. ksort($banknotes);
  6.  
  7. $amountSave = $amount;
  8. $INF = 1000000000;
  9. $minBanknotes = array();
  10. $minBanknotes[0][0] = 0;
  11.  
  12. for($m=0; $m<=$amount; $m++){
  13. $minBanknotes[0][$m] = $m==0?0:$INF;
  14. $p=1;
  15. foreach ($banknotes as $key => $value) {
  16. if($m <= $key-1){
  17. $minBanknotes[$p][$m] = $minBanknotes[$p-1][$m];
  18. }else{
  19. $minBanknotes[$p][$m] = min($minBanknotes[$p-1][$m], $minBanknotes[$p][$m-$key] + 1);
  20. }
  21. $p++;
  22. }
  23. }
  24.  
  25. for($i=count($banknotes);$i>=1;$i--){
  26. $result = array_fill_keys(array_keys($banknotes), 0);
  27. $amount = $amountSave;
  28.  
  29. if ($minBanknotes[$i][$amount]==$INF){
  30. exit("Данным набором банкнот сумму выдать невозможно");
  31. }else{
  32. while($amount>0){
  33. foreach ($minBanknotes[$i] as $key => $value) {
  34. if ($minBanknotes[$i][$amount-$key] == $minBanknotes[$i][$amount]-1){
  35. $result[$key]++;
  36. $amount -= $key;
  37. break;
  38. }
  39. }
  40. }
  41. }
  42.  
  43. $resultStr = "";
  44. foreach ($result as $key => $value) {
  45. if($value != 0){
  46. $resultStr = $resultStr."{$value}x{$key} ";
  47. }
  48. }
  49. echo $resultStr."\n";
  50. }
  51. }
  52.  
  53. $amount = 66;
  54.  
  55. $banknotes = array (
  56. 2 => 3,
  57. 5 => 1,
  58. 20 => 4,
  59. 50 => 1
  60. );
  61.  
  62. echo "Сумма: {$amount}\n";
  63. calculateDelivery($banknotes, $amount);
  64. ?>
Success #stdin #stdout 0.02s 52432KB
stdin
Standard input is empty
stdout
Сумма: 66
3x2 2x5 1x50 
3x2 3x20 
3x2 12x5 
33x2