fork(8) download
  1. /* 잃어버린 괄호 */
  2.  
  3. #include <iostream>
  4. #include <string>
  5. #include <queue>
  6.  
  7. using namespace std;
  8.  
  9. queue<int> i_q; //여기에 각각의 부분합을 넣어줄 것입니다.
  10.  
  11. void take_sub_sum(string); // 부분합 구하는 function입니다.
  12.  
  13. int main(void) {
  14. string in, sub_in;
  15. size_t start_point, minus_point, t;
  16. int sum = 0;
  17.  
  18. start_point = 0;
  19.  
  20. cin >> in; // input을 받는 구간입니다.
  21.  
  22. while (1) {
  23.  
  24. // find 함수를 이용해서 minus의 위치를 얻습니다.
  25.  
  26. minus_point = in.find('-', start_point);
  27.  
  28. // 만약 -의 위치가 npos라면 식이 끝날 때 까지 -가 없다는 의미이므로
  29. // 부분합을 구해주는 take_sub_sum()을 활용합니다.
  30. if (minus_point == string::npos) {
  31. sub_in = in.substr(start_point);
  32. take_sub_sum(sub_in);
  33. break;
  34. }
  35. // 만약 -의 위치를 잘 구했다면 그 - 위치 앞까지 숫자를 분절하고
  36. // 그 숫자 string을 integer로 변환합니다.
  37.  
  38. sub_in = in.substr(start_point, minus_point);
  39.  
  40. start_point = minus_point + 1;
  41.  
  42. take_sub_sum(sub_in);
  43. }
  44.  
  45. /* q에 있는 숫자를 차례대로 꺼내면서 빼면 최소합을 완성할 수 있습니다. */
  46. if (!i_q.empty()) {
  47. sum = i_q.front();
  48. i_q.pop();
  49. }
  50.  
  51. while (!i_q.empty()) {
  52. sum -= i_q.front();
  53. i_q.pop();
  54. }
  55.  
  56. cout << sum << endl;
  57.  
  58. return 0;
  59. }
  60.  
  61. /* 입력받은 문자열을 '+'를 기준으로 분절한 후, stoi 함수를 이용해서
  62.   정수로 바꿔줍니다. 그리고 바꿔준 수를 모두 더해서 i_q에 push합니다. */
  63.  
  64. void take_sub_sum(string expression) {
  65. int sub_total;
  66. string parsed_expression, t;
  67. size_t start_point, plus_position;
  68.  
  69. start_point = 0;
  70. sub_total = 0;
  71. parsed_expression = expression;
  72.  
  73. while (1) {
  74.  
  75. // 1. find 함수를 통해서 '+'의 위치를 찾습니다.
  76. plus_position = parsed_expression.find("+", start_point);
  77.  
  78. // 2. find()가 npos를 return 했다면 식이 끝난 것입니다.
  79. // 그러니 남은 string을 모두 integer로 바꿔서 지금까지 누적된 sub_total에
  80. // 더하고, 이를 i_q에 push합니다. 그리고 return 합니다.
  81.  
  82. if (plus_position == string::npos) {
  83. t = parsed_expression.substr(start_point);
  84. sub_total += stoi(t);
  85. i_q.push(sub_total);
  86. return;
  87. }
  88.  
  89. // substr()을 이용해서 '+'를 포함하지 않은 숫자 string을 얻습니다.
  90. // 그 후 stoi()를 이용해서 이 값을 integer로 바꿔줍니다.
  91.  
  92. t = parsed_expression.substr(start_point, plus_position);
  93. start_point = plus_position + 1;
  94. sub_total += stoi(t);
  95. }
  96. }
Runtime error #stdin #stdout #stderr 0s 4308KB
stdin
10-0-0+1
stdout
Standard output is empty
stderr
terminate called after throwing an instance of 'std::invalid_argument'
  what():  stoi