fork download
  1. #include <stdio.h>
  2.  
  3. int main(void) {
  4. int M;
  5. int price[5]; // a
  6. int stock[5]; // b
  7. int store = 0; // i
  8. long long cost = 0; // 合計金額
  9.  
  10. printf("M?: \n");
  11. scanf("%d", &M);
  12.  
  13. printf("a_i, b_i? (負の値で入力終了):\n");
  14. while (store < 5) {
  15. int p, s;
  16. scanf("%d", &p);
  17. if (p < 0) {
  18. break;
  19. }
  20. scanf("%d", &s);
  21. price[store] = p;
  22. stock[store] = s;
  23. store++;
  24. }
  25.  
  26. for (int i = 0; i < store - 1; i++) {
  27. int min = i; // とりあえずi番目を一番安いと仮定
  28. // i番目より後ろで、もっと安い店がないか探す
  29. for (int j = i + 1; j < store; j++) {
  30. if (price[j] < price[min]) {
  31. min = j; // もっと安い店が見つかったら、その場所を覚える
  32. }
  33. }
  34. int temp_p = price[i];
  35. price[i] = price[min];
  36. price[min] = temp_p;
  37. int temp_s = stock[i];
  38. stock[i] = stock[min];
  39. stock[min] = temp_s;
  40. }
  41.  
  42. int bag = M;
  43. for (int i = 0; i < store; i++) {
  44. if (bag == 0) {
  45. break;
  46. }
  47. int bag_amount;
  48. if (bag <= stock[i]) {
  49. bag_amount = bag;
  50. } else {
  51. bag_amount = stock[i];
  52. }
  53.  
  54. cost += (long long)bag_amount * price[i];
  55. bag -= bag_amount;
  56. }
  57.  
  58. printf("%lld円必要です\n", cost);
  59. return 0;
  60. }
Success #stdin #stdout 0.01s 5276KB
stdin
1200
4
1000
2
1800
10
1400
6
1600
8
-1
stdout
M?: 
a_i, b_i? (負の値で入力終了):
2400円必要です