結果

問題 No.49 算数の宿題
ユーザー not_522not_522
提出日時 2015-07-19 14:23:59
言語 C++11
(gcc 11.4.0)
結果
AC  
実行時間 2 ms / 5,000 ms
コード長 1,637 bytes
コンパイル時間 1,475 ms
コンパイル使用メモリ 164,128 KB
実行使用メモリ 4,380 KB
最終ジャッジ日時 2023-08-24 17:26:21
合計ジャッジ時間 2,084 ms
ジャッジサーバーID
(参考情報)
judge14 / judge12
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 2 ms
4,380 KB
testcase_01 AC 2 ms
4,376 KB
testcase_02 AC 1 ms
4,376 KB
testcase_03 AC 2 ms
4,376 KB
testcase_04 AC 1 ms
4,376 KB
testcase_05 AC 1 ms
4,380 KB
testcase_06 AC 1 ms
4,376 KB
testcase_07 AC 1 ms
4,376 KB
testcase_08 AC 1 ms
4,376 KB
testcase_09 AC 1 ms
4,376 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <bits/stdc++.h>

using namespace std;

template<typename T> inline T toInteger(const string&);

template<> inline int toInteger<int>(const string& s) {
  return stoi(s);
}

template<> inline long toInteger<long>(const string& s) {
  return stol(s);
}

template<> inline long long toInteger<long long>(const string& s) {
  return stoll(s);
}

template<typename T = long long> class Parser {
private:
  string s;
  int p;
  vector<map<char, function<T(T, T)>>> ope;

  T term() {
    if (s[p] == '(') {
      ++p;
      T res = expr(0);
      ++p;
      return res;
    }
    string res = "";
    for (; isdigit(s[p]); ++p) res += s[p];
    return toInteger<T>(res);
  }

  T expr(int level) {
    if (level == (int)ope.size()) return term();
    T res = expr(level + 1);
    for (char c; c = s[p++], ope[level].count(c);) res = ope[level][c](res, expr(level + 1));
    --p;
    return res;
  }

public:
  void addOperator(function<T(T, T)> func, char c, int level) {
    if ((int)ope.size() <= level) ope.resize(level + 1);
    ope[level][c] = func;
  }

  long long parse(const string& s) {
    this->s = s + '@';
    p = 0;
    return expr(0);
  }
};

template<typename T = long long> inline T parse(const string& s) {
  Parser<T> parser;
  parser.addOperator(plus<T>(), '+', 0);
  parser.addOperator(minus<T>(), '-', 0);
  parser.addOperator(multiplies<T>(), '*', 1);
  parser.addOperator(divides<T>(), '/', 1);
  return parser.parse(s);
}

int main() {
  string s;
  cin >> s;
  Parser<> parser;
  parser.addOperator(plus<int>(), '*', 0);
  parser.addOperator(multiplies<int>(), '+', 0);
  cout << parser.parse(s) << endl;
}
0