fork download
  1. #include <iostream>
  2. #include <stack>
  3. #include <string>
  4. #include <sstream>
  5. #include <vector>
  6. using namespace std;
  7.  
  8. int main() {
  9. int t;
  10. cin >> t;
  11. cin.ignore(); // skip newline after t
  12.  
  13. while (t--) {
  14. int n;
  15. cin >> n;
  16. cin.ignore(); // skip newline after n
  17.  
  18. string line;
  19. getline(cin, line); // read the full expression
  20.  
  21. // Tokenize
  22. vector<string> tokens;
  23. stringstream ss(line);
  24. string token;
  25. while (ss >> token) {
  26. tokens.push_back(token);
  27. }
  28.  
  29. if (tokens.size() != n) {
  30. cout << "Invalid Expression" << endl;
  31. continue;
  32. }
  33.  
  34. stack<long long> st;
  35. bool valid = true;
  36.  
  37. for (int i = tokens.size() - 1; i >= 0; --i) {
  38. string tok = tokens[i];
  39.  
  40. if (isdigit(tok[0]) || (tok[0] == '-' && tok.size() > 1)) {
  41. // valid number
  42. st.push(stoll(tok));
  43. } else if (tok == "+" || tok == "-" || tok == "*" || tok == "/") {
  44. if (st.size() < 2) {
  45. valid = false;
  46. break;
  47. }
  48. long long a = st.top(); st.pop();
  49. long long b = st.top(); st.pop();
  50.  
  51. if (tok == "+") st.push(a + b);
  52. else if (tok == "-") st.push(a - b);
  53. else if (tok == "*") st.push(a * b);
  54. else if (tok == "/") {
  55. if (b == 0) {
  56. valid = false;
  57. break;
  58. }
  59. st.push(a / b);
  60. }
  61. } else {
  62. valid = false;
  63. break;
  64. }
  65. }
  66.  
  67. if (valid && st.size() == 1) {
  68. cout << st.top() << endl;
  69. } else {
  70. cout << "Invalid Expression" << endl;
  71. }
  72. }
  73.  
  74. return 0;
  75. }
  76.  
Success #stdin #stdout 0.01s 5312KB
stdin
2
7
+ * - 5 4 100 20
3
- 4 7
stdout
120
-3