fork download
  1. // 種類
  2. // 金額
  3. // 目的額
  4. // 10
  5. // 1 5 10 50 100 500 1000 2000 5000 10000
  6. // 108
  7. // 555
  8. // 9999
  9. // 34567
  10. // 98989
  11. // 123456789
  12.  
  13. #include <iostream>
  14. #include <vector>
  15. #include <map>
  16. #include <algorithm>
  17. using namespace std;
  18.  
  19. const int INF = 1 << 30;
  20.  
  21. int main()
  22. {
  23. int n;
  24. cin >> n;
  25.  
  26. vector<int> v;
  27. for (int i = 0; i < n; ++i)
  28. {
  29. int vv; cin >> vv;
  30. v.push_back(vv);
  31. }
  32. sort(v.begin(), v.end());
  33.  
  34. int mv = v[n - 1];
  35. vector<int> dp(mv * 2 + 1, INF);
  36. vector<map<int, int> > dpp(mv * 2 + 1);
  37. dp[0] = 0;
  38. for (int i = 0; i <= mv * 2; ++i)
  39. for (int j = 0; j < n; ++j)
  40. if (i + v[j] <= mv * 2)
  41. {
  42. if (dp[i] + 1 < dp[i + v[j]])
  43. {
  44. dp[i + v[j]] = dp[i] + 1;
  45. dpp[i + v[j]] = dpp[i];
  46. ++dpp[i + v[j]][j];
  47. }
  48. }
  49.  
  50. int t;
  51. while (cin >> t)
  52. {
  53. int mn = t / mv;
  54. int ct = t - mn * mv;
  55. int re = INF;
  56. int f = 0;
  57. int b = 0;
  58. for (int i = 0; i < ct; ++i)
  59. if (dp[i] + dp[ct + i] < re)
  60. {
  61. re = dp[i] + dp[ct + i];
  62. f = ct + i;
  63. b = i;
  64. }
  65.  
  66. cout << t << ":" << re + mn << endl;
  67. cout << "-> " << f + mn * mv << " ( ";
  68. for (int i = 0; i < n - 1; ++i)
  69. if (dpp[f][i]) cout << v[i] << "x" << dpp[f][i] << " ";
  70. if (mv <= f) ++mn;
  71. if (mn) cout << mv << "x" << mn << " ";
  72. cout << ")" << endl;
  73. cout << "<- " << b << " ( ";
  74. for (int i = 0; i < n - 1; ++i)
  75. if (dpp[b][i]) cout << v[i] << "x" << dpp[b][i] << " ";
  76. cout << ")" << endl;
  77. }
  78.  
  79. return 0;
  80. }
  81.  
Success #stdin #stdout 0.02s 3284KB
stdin
10
1 5 10 50 100 500 1000 2000 5000 10000
108
555
9999
34567
98989
123456789
stdout
108:4
-> 110 ( 10x1 100x1 )
<- 2 ( 1x2 )
555:3
-> 555 ( 5x1 50x1 500x1 )
<- 0 ( )
9999:2
-> 10000 ( 10000x1 )
<- 1 ( 1x1 )
34567:10
-> 35067 ( 1x2 5x1 10x1 50x1 5000x1 10000x3 )
<- 500 ( 500x1 )
98989:13
-> 100000 ( 10000x10 )
<- 1011 ( 1x1 10x1 1000x1 )
123456789:12351
-> 123457000 ( 2000x1 5000x1 10000x12345 )
<- 211 ( 1x1 10x1 100x2 )