fork(1) download
  1. #include <iostream>
  2. #include <cstdlib>
  3. #include <cstring>
  4. #include <ctime>
  5. using namespace std;
  6.  
  7. const int max_n = 50;
  8. int memo[max_n];
  9.  
  10. int count(int n)
  11. {
  12. if (n == 0)
  13. return 1;
  14.  
  15. int &ans = memo[n];
  16. if (ans != -1)
  17. return ans;
  18.  
  19. ans = 0;
  20. for (int i = 0; i < n; ++i)
  21. ans += count(i) * count(n - 1 - i);
  22.  
  23. return ans;
  24. }
  25.  
  26. void bracket(int n)
  27. {
  28. if (n == 0)
  29. return;
  30.  
  31. int r = rand() % count(n);
  32. int left_len = 0;
  33. while (r >= count(left_len) * count(n - 1 - left_len)) {
  34. r -= count(left_len) * count(n - 1 - left_len);
  35. ++left_len;
  36. }
  37. int right_len = n - 1 - left_len;
  38.  
  39.  
  40. cout << '(';
  41. bracket(left_len);
  42. cout << ')';
  43. bracket(right_len);
  44. }
  45.  
  46. int main()
  47. {
  48. srand(time(NULL));
  49.  
  50. int n;
  51. cin >> n;
  52.  
  53. memset(memo, -1, sizeof memo);
  54.  
  55. bracket(n);
  56.  
  57. return 0;
  58. }
Success #stdin #stdout 0s 3416KB
stdin
8
stdout
((()()())())()()