fork(6) download
  1. // Copyright (C) 2015 Katayama Hirofumi MZ. All Rights Reserved.
  2. //
  3. // http://p...content-available-to-author-only...h.net/test/read.cgi/tech/1437736018/
  4. //
  5. // 式 1/2^(a1) + 1/2^(a2) + … + 1/2^(an) = 1
  6. // を満たす非負整数a1~an(ただしa1≦a2≦・・・≦an)を求める
  7. // プログラムをBASICで作りたい。nを適当に指定できるようにして
  8. // すべての解を出力するプログラムを書け。
  9. #include <iostream>
  10. #include <set>
  11. #include <map>
  12. using namespace std;
  13.  
  14. int n;
  15. set<map<int, int> > solutions;
  16.  
  17. void print(const map<int, int>& m) {
  18. for (auto& pair : m) {
  19. for (int i = 0; i < pair.second; ++i) {
  20. cout << pair.first << " ";
  21. }
  22. }
  23. cout << endl;
  24. }
  25.  
  26. int total_count(const map<int, int>& m) {
  27. int c = 0;
  28. for (auto& pair : m) {
  29. c += pair.second;
  30. }
  31. return c;
  32. }
  33.  
  34. void do_it(const map<int, int>& m) {
  35. if (total_count(m) == n) {
  36. solutions.emplace(m);
  37. return;
  38. }
  39. for (auto& pair : m) {
  40. if (pair.second > 0) {
  41. auto m2 = m;
  42. m2[pair.first] -= 1;
  43. m2[pair.first + 1] += 2;
  44. do_it(m2);
  45. }
  46. }
  47. }
  48.  
  49. int main(void) {
  50. cout << "n: ";
  51. cin >> n;
  52.  
  53. map<int, int> m;
  54. m.emplace(0, 1);
  55. do_it(m);
  56.  
  57.  
  58. cout << "solutions: " << endl;
  59. for (auto& ans : solutions) {
  60. print(ans);
  61. }
  62.  
  63. return 0;
  64. }
  65.  
Success #stdin #stdout 0s 3236KB
stdin
10
stdout
n: solutions: 
3 3 3 3 3 3 4 4 4 4 
3 3 3 3 3 3 3 4 5 5 
2 3 3 3 4 4 4 4 4 4 
2 3 3 3 3 4 4 4 5 5 
2 3 3 3 3 3 5 5 5 5 
2 3 3 3 3 3 4 5 6 6 
2 2 4 4 4 4 4 4 4 4 
2 2 3 4 4 4 4 4 5 5 
2 2 3 3 4 4 5 5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