fork download
  1. #include <iostream>
  2. #include <string>
  3. #include <vector>
  4. #include <numeric>
  5. #include <stdexcept>
  6.  
  7. class Solution {
  8. public:
  9. int calPoints(const std::vector<std::string> &ops)
  10. {
  11. std::vector<int> rounds;
  12. int points;
  13.  
  14. for (auto &op : ops)
  15. {
  16. if (op == "C")
  17. {
  18. if (rounds.empty())
  19. throw std::out_of_range("Not enough valid rounds!");
  20.  
  21. rounds.pop_back();
  22. }
  23. else if (op == "D")
  24. {
  25. if (rounds.empty())
  26. throw std::out_of_range("Not enough valid rounds!");
  27.  
  28. points = rounds.back() * 2;
  29. rounds.push_back(points);
  30. }
  31. else if (op == "+")
  32. {
  33. const std::vector<int>::size_type numRounds = rounds.size();
  34. if (numRounds < 2)
  35. throw std::out_of_range("Not enough valid rounds!");
  36.  
  37. points = rounds[numRounds-2] + rounds[numRounds-1];
  38. rounds.push_back(points);
  39. }
  40. else
  41. {
  42. points = std::stoi(op);
  43. rounds.push_back(points);
  44. }
  45. }
  46.  
  47. return std::accumulate(rounds.begin(), rounds.end(), 0);
  48. }
  49. };
  50.  
  51. int main()
  52. {
  53. Solution s;
  54. std::vector<std::string> ops{"5", "2", "C", "D", "+"};
  55. try {
  56. std::cout << s.calPoints(ops);
  57. }
  58. catch (const std::exception &e) {
  59. std::cerr << e.what();
  60. }
  61. return 0;
  62. }
Success #stdin #stdout 0s 4276KB
stdin
Standard input is empty
stdout
30