fork download
  1. #include <iostream>
  2. #include <string>
  3. #include <vector>
  4. #define MAX_POWER 10
  5. using namespace std;
  6.  
  7. void getCoefficients(int* coefficients)
  8. {
  9. int keywords = 1;
  10. vector<string> params;
  11. string begin;
  12. cin >> begin;
  13. params.push_back(((string) "1"));
  14. while (true)
  15. {
  16. string keyword;
  17. cin >> keyword;
  18. if (keyword == (string)"END")
  19. {
  20. keywords--;
  21. params.pop_back();
  22. if (keywords == 0)
  23. {
  24. break;
  25. }
  26. }
  27. else if (keyword == (string)"LOOP")
  28. {
  29. keywords++;
  30. string param;
  31. cin >> param;
  32. params.push_back(param);
  33. }
  34. else if (keyword == (string)"OP")
  35. {
  36. string num;
  37. cin >> num;
  38. int coefficient = stoi(num);
  39. int multiplier = 1, pow = 0;
  40. for (string param : params)
  41. {
  42. if (param == (string)"n")
  43. {
  44. pow++;
  45. }
  46. else
  47. {
  48. multiplier *= stoi(param);
  49. }
  50. }
  51. coefficients[pow] += coefficient * multiplier;
  52. }
  53. }
  54. }
  55.  
  56. string toString(int* coefficients)
  57. {
  58. string result;
  59. for (int i = MAX_POWER; i > 0; i--)
  60. {
  61. if (coefficients[i] != 0)
  62. {
  63. if (coefficients[i] == 1)
  64. {
  65. result += "n";
  66. }
  67. else if (coefficients[i] == -1)
  68. {
  69. result += "-n";
  70. }
  71. else
  72. {
  73. result += to_string(coefficients[i]);
  74. result += "*n";
  75. }
  76. if (i != 1)
  77. {
  78. result += "^";
  79. result += to_string(i);
  80. }
  81. }
  82. if (coefficients[i-1] > 0 && result.length() != 0)
  83. {
  84. result+= "+";
  85. }
  86. }
  87. if (result.length() == 0 || coefficients[0] != 0)
  88. {
  89. result += to_string(coefficients[0]);
  90. }
  91. return result;
  92. }
  93.  
  94. int main()
  95. {
  96. int n;
  97. cin >> n;
  98. int coefficients[MAX_POWER + 1];
  99. for (int i = 1; i <= n; i++)
  100. {
  101. cout << "Program #" << i << endl;
  102. fill(coefficients, coefficients + MAX_POWER + 1, 0);
  103. getCoefficients(coefficients);
  104. cout << "Runtime = " << toString(coefficients) << endl;
  105. if (i != n)
  106. {
  107. cout << endl;
  108. }
  109. }
  110. return 0;
  111. }
Success #stdin #stdout 0s 3468KB
stdin
3
BEGIN
END

BEGIN
LOOP n LOOP n LOOP n OP 1 
LOOP n LOOP n LOOP n OP 1 
LOOP n LOOP n LOOP n OP 1
END END END OP 3
END END END OP 3
END END END OP 3
END 

BEGIN OP 42
LOOP n LOOP 5 LOOP n
OP 7 END OP 2 END OP 1 END
OP 1 END
stdout
Program #1
Runtime = 0

Program #2
Runtime = n^9+4*n^6+4*n^3+3

Program #3
Runtime = 35*n^2+11*n+43