結果

問題 No.708 (+ー)の式
ユーザー peroon
提出日時 2019-06-13 03:54:42
言語 C++14
(gcc 13.3.0 + boost 1.87.0)
結果
AC  
実行時間 2 ms / 2,000 ms
コード長 2,223 bytes
コンパイル時間 1,555 ms
コンパイル使用メモリ 168,768 KB
実行使用メモリ 6,820 KB
最終ジャッジ日時 2024-10-12 10:32:58
合計ジャッジ時間 2,071 ms
ジャッジサーバーID
(参考情報)
judge4 / judge3
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 12
権限があれば一括ダウンロードができます

ソースコード

diff #

#include<bits/stdc++.h>
using namespace std;
using ll = long long;

template<class T>bool chmax(T &a, const T &b) { if (a<b) { a=b; return 1; } return 0; }
template<class T>bool chmin(T &a, const T &b) { if (b<a) { a=b; return 1; } return 0; }

#define FOR(i,a,b) for(ll i=(a);i<(b);++i)
#define ALL(v) (v).begin(), (v).end()
#define p(s) cout<<(s)<<endl
#define p2(s, t) cout << (s) << " " << (t) << endl
#define br() p("")
#define pn(s) cout << (#s) << " " << (s) << endl

// 構文解析セット
// 参考 https://gist.github.com/draftcode/1357281
struct MyParser{
    typedef string::const_iterator State;
    class ParseError {};

    // 外からはこれを使う
    ll parse(string s){
        State it = s.begin();
        ll ans = expression(it);
        return ans;
    }
    ll number(State &begin) {
        ll ret = 0;
        while (isdigit(*begin)) {
            ret *= 10;
            ret += *begin - '0';
            begin++;
        }
        return ret;
    }
    ll factor(State &begin) {
        if (*begin == '(') {
            begin++; // '('を飛ばす。
            ll ret = expression(begin);
            begin++; // ')'を飛ばす。
            return ret;
        } else {
            return number(begin);
        }
    }
    ll term(State &begin) {
        ll ret = factor(begin);
        for (;;) {
            if (*begin == '*') {
                begin++;
                ret *= factor(begin);
            } else if (*begin == '/') {
                begin++;
                ret /= factor(begin);
            } else {
                break;
            }
        }
        return ret;
    }
    ll expression(State &begin) {
        ll ret = term(begin);
        for (;;) {
            if (*begin == '+') {
                begin++;
                ret += term(begin);
            } else if (*begin == '-') {
                begin++;
                ret -= term(begin);
            } else {
                break;
            }
        }
        return ret;
    }
};
// 構文解析セットおわり

int main(){
    cin.tie(0);
    ios::sync_with_stdio(false);

    // input
    string s; cin >> s;
    auto pa = MyParser();
    ll ans = pa.parse(s);
    p(ans);
    
    return 0;
}
0