Subtask #0 全部 rt可能原因
查看原帖
Subtask #0 全部 rt可能原因
1544265
AK47are楼主2024/12/1 18:10

Subtask #0 的测试全是用 \r\n 结尾的。被这个坑惨了,查这个花了一下午。

#include <bits/stdc++.h>
using namespace std;
string GetSuffix();

int main() {
  string expr = GetSuffix();
  vector<int> s;
  for (int i = 0; i < expr.size(); ++i) {
    if (isdigit(expr[i])) {
      s.push_back(expr[i] - '0');
    } else {
      for (int j = 0; j < s.size(); ++j) {
        cout << s[j] << " ";
      }
      for (int j = i; j < expr.size(); ++j) {
        cout << expr[j] << " ";
      }
      cout << "\n";
      int y = s.back();
      s.pop_back();
      int x = s.back();
      s.pop_back();
      switch (expr[i]) {
        case '+':
          s.push_back(x + y);
          break;
        case '-':
          s.push_back(x - y);
          break;
        case '*':
          s.push_back(x * y);
          break;
        case '/':
          s.push_back(x / y);
          break;
        case '^':
          s.push_back(pow(x, y));
          break;
      }
    }
  }
  cout << s.front() << "\n";
}

int Priority(char c) {
  switch (c) {
    case '+':
    case '-':
      return 1;
    case '*':
    case '/':
      return 2;
    case '^':
      return 3;
    default:
      return -1;
  }
}

string GetSuffix() {
  string expr;
  stack<char> op;
  // 不能使用 c != '\n' 判断。
  for (char c = cin.get(); c != '\r' && c != '\n'; c = cin.get()) {
    if (isdigit(c)) {
      expr.push_back(c);
    } else if (c == '(') {
      op.push(c);
    } else if (c == ')') {
      while (op.top() != '(') {
        expr.push_back(op.top());
        op.pop();
      }
      op.pop();
    } else {
      while (!op.empty() && Priority(op.top()) >= Priority(c)) {
        if (op.top() == '^' && c == '^') break;
        expr.push_back(op.top());
        op.pop();
      }
      op.push(c);
    }
  }
  while (!op.empty()) {
    expr.push_back(op.top());
    op.pop();
  }
  return expr;
}
2024/12/1 18:10
加载中...