Problem:
小野小町の編集合戦
近所に住む秋田博士は在野の歴史研究家であり, 最近小野小町に関する新たな古文書を発見したそうだ.
小野小町が交際を望む深草少将に100夜欠かさず通い続けることを条件に出したという伝説は広く知られているが, 彼の主張によると, この発見により新たに, 2人は毎晩とあるゲームをしていたことがわかったという.
そのルールは以下の通りである.
最初に召使が編集回数と有効な数式を決める
深草少将, 小野小町, 深草少将, 小野小町,... という順に交互に数式を編集する
深草少将と小野小町が合わせて召使が決めた回数の編集を行うとゲームは終了する
1回の数式の編集において, 数式に 1 文字追加, または数式から 1 文字削除のいずれかができる
数式が無効になるような編集をしてはならない
有効な数式の詳しい定義は下記を見てほしい.
このゲームにおいて, 最終的な数式の計算結果が大きいほど,
深草少将の通うべき日数を減らしてあげることになっていたらしい.
すなわち, 深草少将は結果を最大化させることが目的であり,
小野小町は最小化させることが目的である.
ところで, 古文書には召使が決めた編集回数と数式については記録が残っていたのであるが,
肝心の結果の方は虫食いにより読めなくなってしまっていた.
博士は結果に興味を持ち, 自力で計算してみようと思ったものの, ゲーム理論が得意でない彼には難しすぎたため, とりあえず近所のあなたに助けを求めてきたようだ.
そこであなたはプログラムを書いて彼に協力することにした.
平安時代に現代的な数式があったということに胡散臭さを感じるかもしれないが, 近所付き合いという大義の前に, そのような些事を気にするべきではないのだ.
有効な数式の定義
このゲームにおける有効な数式とは, "(", ")", "*", "+", "-", "&", "^", "|", "0" - "9" の 18 種類の文字のみからなる空でない文字列であり,
さらに, 有限個の項を2項演算子で結合したものである.
書き下すと,
[項][2項演算子][項][2項演算子]...[2項演算子][項]
のようになる.
項とは, "("[有効な数式]")" のようにカッコで挟まれた有効な数式, または正の整数である.
正の整数は, 先頭に "0" を持たない, 数字のみからなる文字列である.
最後に, 2項演算子とは, "*", "+", "-", "&", "^", "|" のいずれかちょうど 1 文字である.
詳しい定義は下記を見てほしい.
以上の規則から,
"1+-1" のように2文字あるので有効な2項演算子でないもの,
"+1" のように項を2項演算子で結合したものでないもの,
"2)", "(3" のようにカッコの対応がとれていないので有効な項でないもの,
"0", "01" のように 0 で始まり有効な正の整数の表現でないもの
などは, 無効な数式であるとみなされる.
一方で,
"(1+2)" のように最も外側にカッコが付いているもの,
"((1+2))*3" のように2重にカッコが付いているもの,
"(1)+3" のように括弧内に数しかないもの,
"(1*2)+3" のように2項演算子の優先順位と同じになるもの,
などは, 冗長ではあるが, 上の規則の下では受理され, 有効な数式とみなされることに注意してほしい.
2項演算子の種類
このゲームにおいて, 2項演算子は "*", "+", "-", "&", "^", "|" の 6 種類がある.
それぞれ, 乗算, 加算, 減算, ビットごとの論理積, ビットごとの排他的論理和, ビットごとの論理和である.
なお, ビット演算を考えるとき, 負の数は十分大きな桁数の2の補数で表現されていると見なされる. すなわち, 普通の符号付き整数型で計算すると考えてもよい.
また, 優先順位は高い方から,
*
+, -
&
^
|
の順である.
なお, + より * の方が優先順位が高いとは,
2*4+3*5
のような式において * のほうが先に計算されるという意味であり, 言い換えると,
(2*4)+(3*5)
となるということである.
また, すべての2項演算子は左結合であるとする.
これは,
2^4^3^5
のような式において左から順に計算するという意味であり, 言い換えると,
((2^4)^3)^5
となるということである.
Input
入力は複数のデータセットから構成される. 各データセットは1回のゲームで召使が決めた編集回数と数式を表し, その形式は以下の通りである.
N
Expression
N
は召使が決めた編集回数であり, 1 ≤
N
≤ 11 と仮定してよい.
また,
Expression
は召使が決めた数式であり, "(", ")", "*", "+", "-", "&", "^", "|", "0" - "9" の 18 種類の文字のみからなる, 7 文字以下の空でない文字列として与えられる.
なお, 上で定義した有効な数式のみが与えられ, 無効な数式が与えられることはないと仮定してよい.
入力の終わりは,
0
#
で表される.
なお, データセットは 99 個以下であると仮定してよい.
Output
各データセットに対して, 両者が最善を尽くしたときの最終的な数式の計算結果を 1 行で出力せよ.
それ以外の余計な文字を出力してはならない.
Sample Input
1 1
2 2
3 1+2*3-4
3 1|2^3&4
3 (1+2)*3
3 1-1-1-1
0 #
Output for Sample Input
91
2
273
93
279
88

Submitted solutions:

code_snippet: #include <bits/stdc++.h>
using namespace std;

constexpr int INF = 1e9;

int expr(string const& s, int& p);
int Or(string const& s, int& p);
int Xor(string const& s, int& p);
int And(string const& s, int& p);
int Plus(string const& s, int& p);
int term(string const& s, int& p);
int factor(string const& s, int& p);
int number(string const& s, int& p);

int expr(string const& s, int& p) {
    return Or(s, p);
}

int Or(string const& s, int& p) {
    int res = Xor(s, p);
    while(p < s.size() && s[p] == '|') {
        res |= Xor(s, ++p);
    }
    return res;
}

int Xor(string const& s, int& p) {
    int res = And(s, p);
    while(p < s.size() && s[p] == '^') {
        res ^= And(s, ++p);
    }
    return res;
}

int And(string const& s, int& p) {
    int res = Plus(s, p);
    while(p < s.size() && s[p] == '&') {
        res &= Plus(s, ++p);
    }
    return res;
}

int Plus(string const& s, int& p) {
    int res = term(s, p);
    while(p < s.size() && (s[p] == '+' || s[p] == '-')) {
        char op = s[p++];
        if(op == '+') {
            res += term(s, p);
        } else {
            res -= term(s, p);
        }
    }
    return res;
}

int term(string const& s, int& p) {
    int res = factor(s, p);
    while(p < s.size() && s[p] == '*') {
        res *= factor(s, ++p);
    }
    return res;
}

int factor(string const& s, int& p) {
    if(isdigit(s[p])) {
        if(s[p] == '0') {
            throw runtime_error("");
        }
        return number(s, p);
    }
    if(s[p] == '(') {
        int res = expr(s, ++p);
        ++p;
        return res;
    }
    throw runtime_error("");
}

int number(string const& s, int& p) {
    int res = 0;
    while(p < s.size() && isdigit(s[p])) {
        res *= 10;
        res += s[p++] - '0';
    }
    return res;
}


string pattern = "0123456789*+-&^|";

int parse(string const& s) {
    try {
        int p = 0;
        int t = expr(s, p);
        if(p != s.size()) {
            return INF;
        }
        return t;
    } catch(...) {
        return INF;
    }
}

int solve(string s, int cnt, int turn) {
    if(cnt == 0) {
        return parse(s);
    }
    int res = (turn == 0 ? -INF : INF);
    // erase
    for(int i=0; i<s.size(); ++i) {
        string t = s;
        t.erase(t.begin()+i);
        if(t.size() == 0 || INF == parse(t)) {
            continue;
        }
        int tmp = solve(t, cnt-1, turn^1);
        if(tmp == INF) {
            continue;
        }
        if(turn == 0) {
            res = max(res, tmp);
        } else {
            res = min(res, tmp);
        }
    }

    // insert
    for(int i=0; i<pattern.size(); ++i) {
        for(int j=0; j<=s.size(); ++j) {
            string t = s;
            t.insert(t.begin()+j, pattern[i]);
            if(INF == parse(t)) {
                continue;
            }
            int tmp = solve(t, cnt-1, turn^1);
            if(tmp == INF) {
                continue;
            }
            if(turn == 0) {
                res = max(res, tmp);
            } else {
                res = min(res, tmp);
            }
        }
        
    }
    return res;
}


int main() {
    int n;
    string s;
    while(cin >> n >> s, n) {
        if(n & 1) {
            cout << solve(s, 1, 0) << endl;
        } else {
            cout << solve(s, 2, 0) << endl;
        }
    }
}
accuracy: 1
time_ms: 390
memory_kb: 3524
final_rank: 15

code_snippet: // AOJ #2512 Ononokomachi's Edit War
// 2025.4.25

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

struct Parser {
    using It = const char*;
    static const string ops;
    int eval(const string &s) const {
        It it = s.c_str();
        return expr(it, 4);
    }

  private:
    int expr(It &it, int prec) const {
        if (prec >= 0) {
            int v = expr(it, prec - 1);
            while (*it && matchOp(*it, ops[prec])) {
                char op = *it++;
                int r = expr(it, prec - 1);
                v = apply(v, r, op);
            }
            return v;
        }
        if (*it == '(') {
            ++it;
            int v = expr(it, 4);
            ++it;
            return v;
        }
        int v = 0;
        while (*it && isdigit(*it)) v = v * 10 + (*it++ - '0');
        return v;
    }

    static bool matchOp(char c, char code) {
        return code == '!' ? (c == '+' || c == '-') : (c == code);
    }
    static int apply(int a, int b, char op) {
        switch (op) {
            case '*': return a * b;
            case '+': return a + b;
            case '-': return a - b;
            case '&': return a & b;
            case '^': return a ^ b;
            case '|': return a | b;
        }
        return 0;
    }
};

int n;
const string Parser::ops = "*!&^|";
const string DIGITS  = "0123456789";
const string INS_OPS = "*+-&^|";
Parser ps;

vector<string> genVec(const string &s) {
    int m = s.size();
    vector<string> R;
    R.reserve((m + 1) * (DIGITS.size() + INS_OPS.size()) + m);
    for (int i = 0; i <= m; ++i) {
        bool lef = (i > 0 && isdigit(s[i - 1]));
        bool rig = (i < m && isdigit(s[i]));
        for (char d : DIGITS) {
            if (lef || (rig && d != '0')) {
                string t; t.reserve(m + 1);
                t = s;
                t.insert(t.begin() + i, d);
                R.push_back(move(t));
            }
        }
        for (char op : INS_OPS) {
            if (lef && rig && s[i] != '0') {
                string t; t.reserve(m + 1);
                t = s;
                t.insert(t.begin() + i, op);
                R.push_back(move(t));
            }
        }
    }
    for (int i = 0; i < m; ++i) {
        bool lef = (i > 0 && isdigit(s[i - 1]));
        bool rig = (i + 1 < m && isdigit(s[i + 1]));
        if (isdigit(s[i])) {
            if (lef || (rig && s[i + 1] != '0')) {
                string t; t.reserve(m);
                t = s;
                t.erase(t.begin() + i);
                R.push_back(move(t));
            }
        } else {
            if (lef && rig) {
                string t; t.reserve(m);
                t = s;
                t.erase(t.begin() + i);
                R.push_back(move(t));
            }
        }
    }
    sort(R.begin(), R.end());
    R.erase(unique(R.begin(), R.end()), R.end());
    return R;
}

static unordered_map<string,int> evalCache;
int eval_cached(const string &t) {
    auto it = evalCache.find(t);
    if (it != evalCache.end()) return it->second;
    int v = ps.eval(t);
    evalCache.emplace(t, v);
    return v;
}

int solveGame(const string &s) {
    evalCache.clear();
    evalCache.reserve(512);

    auto S1 = genVec(s);
    int best = INT_MIN;
    if (n & 1) {
        for (auto &t1 : S1) best = max(best, eval_cached(t1));
    } else {
        for (auto &t1 : S1) {
            int mn = INT_MAX;
            auto S2 = genVec(t1);
            for (auto &t2 : S2) mn = min(mn, eval_cached(t2));
            best = max(best, mn);
        }
    }
    return best;
}

int main(){
    ios::sync_with_stdio(0);
    cin.tie(0);
    while (true) {
        string S;
        cin >> n >> S;
        if (n == 0) break;
        cout << solveGame(S) << endl;
    }
    return 0;
}
accuracy: 1
time_ms: 50
memory_kb: 3936
final_rank: 8

code_snippet: // AOJ #2512 Ononokomachi's Edit War
// 2025.4.25

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

struct Parser {
    using It = string::const_iterator;
    static const string ops;

    int eval(const string &s) const {
        It it = s.begin();
        return expr(it, 4);
    }

  private:
    int expr(It &it, int prec) const {
        if (prec >= 0) {
            int v = expr(it, prec - 1);
            while (it != s_end && matchOp(*it, ops[prec])) {
                char op = *it++;
                int r = expr(it, prec - 1);
                v = apply(v, r, op);
            }
            return v;
        }
        if (*it == '(') {
            ++it;
            int v = expr(it, 4);
            ++it;
            return v;
        }
        int v = 0;
        while (it != s_end && isdigit(*it)) {
            v = v * 10 + (*it - '0');
            ++it;
        }
        return v;
    }

    static bool matchOp(char c, char code) {
        if (code == '!') return c == '+' || c == '-';
        return c == code;
    }
    static int apply(int a, int b, char op) {
        switch (op) {
            case '*': return a * b;
            case '+': return a + b;
            case '-': return a - b;
            case '&': return a & b;
            case '^': return a ^ b;
            case '|': return a | b;
        }
        return 0;
    }
    static constexpr It s_end = It();
};

int n;
const string Parser::ops = "*!&^|";
static Parser ps;
static const string DIGITS  = "0123456789";
static const string INS_OPS = "*+-&^|";

unordered_set<string> gen(const string &s) {
    int m = s.size();
    unordered_set<string> R;
    R.reserve((m + 1) * (DIGITS.size() + INS_OPS.size()));
    for (int i = 0; i <= m; ++i) {
        bool leftNum  = (i > 0 && isdigit(s[i - 1]));
        bool rightNum = (i < m && isdigit(s[i]));
        for (char d : DIGITS) {
            if (leftNum || (rightNum && d != '0')) {
                string t = s;
                t.insert(t.begin() + i, d);
                R.insert(move(t));
            }
        }
        for (char op : INS_OPS) {
            if (leftNum && rightNum && s[i] != '0') {
                string t = s;
                t.insert(t.begin() + i, op);
                R.insert(move(t));
            }
        }
    }
    for (int i = 0; i < m; ++i) {
        bool leftNum  = (i > 0 && isdigit(s[i - 1]));
        bool rightNum = (i + 1 < m && isdigit(s[i + 1]));
        if (isdigit(s[i])) {
            if (leftNum || (rightNum && s[i + 1] != '0')) {
                string t = s;
                t.erase(t.begin() + i);
                R.insert(move(t));
            }
        } else {
            if (leftNum && rightNum) {
                string t = s;
                t.erase(t.begin() + i);
                R.insert(move(t));
            }
        }
    }
    return R;
}

static unordered_map<string,int> evalCache;

int eval_cached(const string &t) {
    auto it = evalCache.find(t);
    if (it != evalCache.end()) return it->second;
    int v = ps.eval(t);
    evalCache.emplace(t, v);
    return v;
}

int solve(const string &s) {
    evalCache.clear();
    evalCache.reserve(1024);

    auto S1 = gen(s);
    int best = INT_MIN;

    if (n & 1) {
        for (const auto &t1 : S1) best = max(best, eval_cached(t1));
    } else {
        for (const auto &t1 : S1) {
            auto S2 = gen(t1);
            int mn = INT_MAX;
            for (const auto &t2 : S2) mn = min(mn, eval_cached(t2));
            best = max(best, mn);
        }
    }
    return best;
}

int main(){
    ios::sync_with_stdio(0);
    cin.tie(0);
    evalCache.reserve(4096);
    while (true) {
        string S;
        cin >> n >> S;
        if (n == 0) break;
        cout << solve(S) << endl;
    }
    return 0;
}
accuracy: 1
time_ms: 50
memory_kb: 3848
final_rank: 7

code_snippet: // AOJ #2512 Ononokomachi's Edit War
// 2025.4.25

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

struct Parser {
    using It = string::const_iterator;
    static const string ops;
    int eval(const string &s) {
        It it = s.begin();
        return expr(it, 4);
    }

  private:
    int expr(It &it, int prec) {
        if (prec >= 0) {
            int v = expr(it, prec-1);
            while (*it && matchOp(*it, ops[prec])) {
                char op = *it++;
                int r = expr(it, prec-1);
                v = apply(v, r, op);
            }
            return v;
        }
        if (*it == '(') {
            ++it;
            int v = expr(it, 4);
            it++;
            return v;
        }
        int v = 0;
        while (*it && isdigit(*it)) v = v*10 + (*it++ - '0');
        return v;
    }

    static bool matchOp(char c, char code) {
        if (code == '!') return c=='+' || c=='-';
        return c == code;
    }
    static int apply(int a, int b, char op) {
        switch(op) {
            case '*': return a*b;
            case '+': return a+b;
            case '-': return a-b;
            case '&': return a&b;
            case '^': return a^b;
            case '|': return a|b;
        }
        return 0;
    }
};

int n;
const string Parser::ops = "*!&^|";
Parser ps;
const string DIGITS  = "0123456789";
const string INS_OPS = "*+-&^|";

set<string> gen(const string &s) {
    set<string> R;
    int m = s.size();
    for (int i = 0; i <= m; ++i) {
        bool leftNum  = (i>0    && isdigit(s[i-1]));
        bool rightNum = (i<m    && isdigit(s[i]));
        for (char d : DIGITS) {
            if (leftNum || (rightNum && d!='0')) {
                string t = s;
                t.insert(t.begin()+i, d);
                R.insert(t);
            }
        }
        for (char op : INS_OPS) {
            if (leftNum && rightNum && s[i]!='0') {
                string t = s;
                t.insert(t.begin()+i, op);
                R.insert(t);
            }
        }
    }
    for (int i = 0; i < m; ++i) {
        bool leftNum  = (i>0     && isdigit(s[i-1]));
        bool rightNum = (i+1<m   && isdigit(s[i+1]));
        if (isdigit(s[i])) {
            if (leftNum || (rightNum && s[i+1]!='0')) {
                string t = s;
                t.erase(t.begin()+i);
                R.insert(t);
            }
        } else {
            if (leftNum && rightNum) {
                string t = s;
                t.erase(t.begin()+i);
                R.insert(t);
            }
        }
    }
    return R;
}

int solve(const string &s) {
    auto S1 = gen(s);
    int best = INT_MIN;
    if (n & 1) {
        for (auto &t1 : S1) {
            best = max(best, ps.eval(t1));
        }
    } else {
        for (auto &t1 : S1) {
            int mn = INT_MAX;
            auto S2 = gen(t1);
            for (auto &t2 : S2) mn = min(mn, ps.eval(t2));
            best = max(best, mn);
        }
    }
    return best;
}

int main(){
    ios::sync_with_stdio(0);
    cin.tie(0);
    while (true) {
        string S;
        cin >> n >> S;
        if (n == 0) break;
        cout << solve(S) << endl;
    }
    return 0;
}
accuracy: 1
time_ms: 40
memory_kb: 3432
final_rank: 5

code_snippet: #include "bits/stdc++.h"
using namespace std;
using ll = long long;
using ld = long double;
using ull = unsigned long long;
#define rep(i, m, n) for (ll i = (ll)m; i < (ll)n; i++)
#define drep(i, m, n) for (ll i = m - 1; i >= n; i--)
#define Endl endl
#define all(a) a.begin(), a.end()
#define pr(i, j) make_pair(i, j)
#define isin(x, l, r) (l <= x && x < r)
#define chmin(a, b) a = min(a, b)
#define chmax(a, b) a = max(a, b)
#define srt(ar) sort(ar.begin(), ar.end())
#define rev(ar) reverse(ar.begin(), ar.end())
#define jge(f, s, t) cout << (f ? s : t) << endl
#pragma GCC target("avx2")
#pragma GCC optimize("O3")
#pragma GCC optimize("unroll-loops")

#define printar(ar)             \
    do                          \
    {                           \
        for (auto dbg : ar)     \
        {                       \
            cout << dbg << " "; \
        }                       \
        cout << endl;           \
    } while (0)
const ll inf = 1e18;
const ld pi = 3.14159265358979;
const ld eps = 1e-9;
template <class T, ll n, ll idx = 0>
auto make_vec(const ll (&d)[n], const T &init) noexcept
{
    if constexpr (idx < n)
        return std::vector(d[idx], make_vec<T, n, idx + 1>(d, init));
    else
        return init;
}

template <class T, ll n>
auto make_vec(const ll (&d)[n]) noexcept
{
    return make_vec(d, T{});
}
//////////////// 以下を貼る ////////////////
template <class T>
size_t HashCombine(const size_t seed, const T &v)
{
    return seed ^ (std::hash<T>()(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2));
}
/* pair用 */
template <class T, class S>
struct std::hash<std::pair<T, S>>
{
    size_t operator()(const std::pair<T, S> &keyval) const noexcept
    {
        return HashCombine(std::hash<T>()(keyval.first), keyval.second);
    }
};
////////////////////////////////////////////
ll exp1(string &s, int &idx);
ll exp2(string &s, int &idx);
ll exp3(string &s, int &idx);
ll exp4(string &s, int &idx);
ll exp5(string &s, int &idx);
ll exp6(string &s, int &idx);
ll number(string &s, int &idx);
ll exp1(string &s, int &idx)
{
    ll v1 = exp2(s, idx);
    while (idx < (int)s.length() && s[idx] == '|')
    {
        idx++;
        ll v2 = exp2(s, idx);
        v1 |= v2;
    }
    return v1;
}
ll exp2(string &s, int &idx)
{
    ll v1 = exp3(s, idx);
    while (idx < (int)s.length() && s[idx] == '^')
    {
        idx++;
        ll v2 = exp3(s, idx);
        v1 ^= v2;
    }
    return v1;
}
ll exp3(string &s, int &idx)
{
    ll v1 = exp4(s, idx);
    while (idx < (int)s.length() && s[idx] == '&')
    {
        idx++;
        ll v2 = exp4(s, idx);
        v1 &= v2;
    }
    return v1;
}
ll exp4(string &s, int &idx)
{
    ll v1 = exp5(s, idx);
    while (idx < (int)s.length() && (s[idx] == '+' || s[idx] == '-'))
    {
        char op = s[idx];
        idx++;
        ll v2 = exp5(s, idx);
        if (op == '+')
        {
            v1 += v2;
        }
        else
        {
            v1 -= v2;
        }
    }
    return v1;
}
ll exp5(string &s, int &idx)
{
    ll v1 = exp6(s, idx);
    while (idx < (int)s.length() && s[idx] == '*')
    {
        idx++;
        ll v2 = exp6(s, idx);
        v1 *= v2;
    }
    return v1;
}
ll exp6(string &s, int &idx)
{
    if (isdigit(s[idx]))
    {
        return number(s, idx);
    }
    else
    {
        idx++;
        ll ret = exp1(s, idx);
        idx++;
        return ret;
    }
}
ll number(string &s, int &idx)
{
    string t = "";
    while (idx < (int)s.length() && isdigit(s[idx]))
    {
        t += s[idx];
        idx++;
    }
    return stoll(t);
}
ll F(ll remain, bool turn, string S)
{
    if (remain == 0)
    {
        int idx = 0;
        string u = S;
        ll x = exp1(u, idx);
        return x;
    }
    else
    {
        ll m = 0;
        if (turn)
        {
            m = -inf;
        }
        else
        {
            m = inf;
        }
        rep(i, 0, S.length() + 1)
        {
            bool f = false;
            if (i < S.length() && isdigit(S[i]))
            {
                f = true;
            }
            bool g = false;
            if (i - 1 >= 0 && isdigit(S[i - 1]))
            {
                g = true;
            }
            if (!f && !g)
            {
                continue;
            }
            for (char j = '0'; j <= '9'; j++)
            {
                if (j == '0' && !g)
                {
                    continue;
                }
                string t = S.substr(0, i);
                t.push_back(j);
                if (i != S.length())
                {
                    t += S.substr(i);
                }
                ll x = F(remain - 1, !turn, t);
                if (turn)
                {
                    chmax(m, x);
                }
                else
                {
                    chmin(m, x);
                }
            }
            if (f && g)
            {
                vector<char> ar = {'+', '-', '*', '|', '&', '^'};
                for (char j : ar)
                {
                    if (S[i] == '0')
                    {
                        continue;
                    }
                    string t = S.substr(0, i);
                    t.push_back(j);
                    if (i != S.length())
                    {
                        t += S.substr(i);
                    }
                    ll x = F(remain - 1, !turn, t);
                    if (turn)
                    {
                        chmax(m, x);
                    }
                    else
                    {
                        chmin(m, x);
                    }
                }
            }
        }
        if (S.length() != 1)
        {
            rep(i, 0, S.length())
            {
                if (S[i] == '(' || S[i] == ')')
                {
                    continue;
                }
                bool f = false;
                if (i - 1 >= 0 && isdigit(S[i - 1]))
                {
                    f = true;
                }
                bool g = false;
                if (i + 1 < S.length() && isdigit(S[i + 1]))
                {
                    g = true;
                }
                if (!f && !g)
                {
                    continue;
                }
                if (!isdigit(S[i]))
                {
                    if (!f || !g)
                    {
                        continue;
                    }
                }
                if (!f && S[i + 1] == '0')
                {
                    continue;
                }
                string t = S.substr(0, i);
                if (i != S.length() - 1)
                {
                    t += S.substr(i + 1);
                }
                ll x = F(remain - 1, !turn, t);
                if (turn)
                {
                    chmax(m, x);
                }
                else
                {
                    chmin(m, x);
                }
            }
        }
        return m;
    }
}
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    while (true)
    {
        ll n;
        string S;
        cin >> n >> S;
        if (n == 0)
        {
            break;
        }
        if (n % 2 == 1)
        {
            cout << F(1, true, S) << endl;
        }
        else if (n % 2 == 0)
        {
            cout << F(2, true, S) << endl;
        }
    }
}
accuracy: 1
time_ms: 20
memory_kb: 3456
final_rank: 3

code_snippet: #include <bits/stdc++.h>

using namespace std;

#define rep(i, a, b) for (int i = (int)(a); i < (int)(b); i++)
#define rrep(i, a, b) for (int i = (int)(b)-1; i >= (int)(a); i--)
#define ALL(v) (v).begin(), (v).end()
#define UNIQUE(v) sort(ALL(v)), (v).erase(unique(ALL(v)), (v).end())
#define SZ(v) (int)v.size()
#define MIN(v) *min_element(ALL(v))
#define MAX(v) *max_element(ALL(v))
#define LB(v, x) int(lower_bound(ALL(v), (x)) - (v).begin())
#define UB(v, x) int(upper_bound(ALL(v), (x)) - (v).begin())

using uint = unsigned int;
using ll = long long int;
using ull = unsigned long long;
using i128 = __int128_t;
using u128 = __uint128_t;
const int inf = 0x3fffffff;
const ll INF = 0x1fffffffffffffff;

template <typename T> inline bool chmax(T &a, T b) {
    if (a < b) {
        a = b;
        return 1;
    }
    return 0;
}
template <typename T> inline bool chmin(T &a, T b) {
    if (a > b) {
        a = b;
        return 1;
    }
    return 0;
}
template <typename T, typename U> T ceil(T x, U y) {
    assert(y != 0);
    if (y < 0)
        x = -x, y = -y;
    return (x > 0 ? (x + y - 1) / y : x / y);
}
template <typename T, typename U> T floor(T x, U y) {
    assert(y != 0);
    if (y < 0)
        x = -x, y = -y;
    return (x > 0 ? x / y : (x - y + 1) / y);
}
template <typename T> int popcnt(T x) {
    return __builtin_popcountll(x);
}
template <typename T> int topbit(T x) {
    return (x == 0 ? -1 : 63 - __builtin_clzll(x));
}
template <typename T> int lowbit(T x) {
    return (x == 0 ? -1 : __builtin_ctzll(x));
}

template <class T, class U>
ostream &operator<<(ostream &os, const pair<T, U> &p) {
    os << "P(" << p.first << ", " << p.second << ")";
    return os;
}
template <typename T> ostream &operator<<(ostream &os, const vector<T> &vec) {
    os << "{";
    for (int i = 0; i < vec.size(); i++) {
        os << vec[i] << (i + 1 == vec.size() ? "" : ", ");
    }
    os << "}";
    return os;
}
template <typename T, typename U>
ostream &operator<<(ostream &os, const map<T, U> &map_var) {
    os << "{";
    for (auto itr = map_var.begin(); itr != map_var.end(); itr++) {
        os << "(" << itr->first << ", " << itr->second << ")";
        itr++;
        if (itr != map_var.end())
            os << ", ";
        itr--;
    }
    os << "}";
    return os;
}
template <typename T> ostream &operator<<(ostream &os, const set<T> &set_var) {
    os << "{";
    for (auto itr = set_var.begin(); itr != set_var.end(); itr++) {
        os << *itr;
        ++itr;
        if (itr != set_var.end())
            os << ", ";
        itr--;
    }
    os << "}";
    return os;
}
#ifdef LOCAL
#define show(...) _show(0, #__VA_ARGS__, __VA_ARGS__)
#else
#define show(...) true
#endif
template <typename T> void _show(int i, T name) {
    cerr << '\n';
}
template <typename T1, typename T2, typename... T3>
void _show(int i, const T1 &a, const T2 &b, const T3 &...c) {
    for (; a[i] != ',' && a[i] != '\0'; i++)
        cerr << a[i];
    cerr << ":" << b << " ";
    _show(i + 1, a, c...);
}

#include <unistd.h>

namespace fastio {
static constexpr uint32_t SZ = 1 << 17;
char ibuf[SZ];
char obuf[SZ];
char out[100];
// pointer of ibuf, obuf


uint32_t pil = 0, pir = 0, por = 0;

struct Pre {
    char num[10000][4];
    constexpr Pre() : num() {
        for (int i = 0; i < 10000; i++) {
            int n = i;
            for (int j = 3; j >= 0; j--) {
                num[i][j] = n % 10 | '0';
                n /= 10;
            }
        }
    }
} constexpr pre;

inline void load() {
    memmove(ibuf, ibuf + pil, pir - pil);
    pir = pir - pil + fread(ibuf + pir - pil, 1, SZ - pir + pil, stdin);
    pil = 0;
    if (pir < SZ)
        ibuf[pir++] = '\n';
}

inline void flush() {
    fwrite(obuf, 1, por, stdout);
    por = 0;
}

void rd(char &c) {
    do {
        if (pil + 1 > pir)
            load();
        c = ibuf[pil++];
    } while (isspace(c));
}

void rd(string &x) {
    x.clear();
    char c;
    do {
        if (pil + 1 > pir)
            load();
        c = ibuf[pil++];
    } while (isspace(c));
    do {
        x += c;
        if (pil == pir)
            load();
        c = ibuf[pil++];
    } while (!isspace(c));
}

template <typename T> void rd_real(T &x) {
    string s;
    rd(s);
    x = stod(s);
}

template <typename T> void rd_integer(T &x) {
    if (pil + 100 > pir)
        load();
    char c;
    do
        c = ibuf[pil++];
    while (c < '-');
    bool minus = 0;
    if constexpr (is_signed<T>::value || is_same_v<T, i128>) {
        if (c == '-') {
            minus = 1, c = ibuf[pil++];
        }
    }
    x = 0;
    while ('0' <= c) {
        x = x * 10 + (c & 15), c = ibuf[pil++];
    }
    if constexpr (is_signed<T>::value || is_same_v<T, i128>) {
        if (minus)
            x = -x;
    }
}

void rd(int &x) {
    rd_integer(x);
}
void rd(ll &x) {
    rd_integer(x);
}
void rd(i128 &x) {
    rd_integer(x);
}
void rd(uint &x) {
    rd_integer(x);
}
void rd(ull &x) {
    rd_integer(x);
}
void rd(u128 &x) {
    rd_integer(x);
}
void rd(double &x) {
    rd_real(x);
}
void rd(long double &x) {
    rd_real(x);
}

template <class T, class U> void rd(pair<T, U> &p) {
    return rd(p.first), rd(p.second);
}
template <size_t N = 0, typename T> void rd_tuple(T &t) {
    if constexpr (N < std::tuple_size<T>::value) {
        auto &x = std::get<N>(t);
        rd(x);
        rd_tuple<N + 1>(t);
    }
}
template <class... T> void rd(tuple<T...> &tpl) {
    rd_tuple(tpl);
}

template <size_t N = 0, typename T> void rd(array<T, N> &x) {
    for (auto &d : x)
        rd(d);
}
template <class T> void rd(vector<T> &x) {
    for (auto &d : x)
        rd(d);
}

void read() {}
template <class H, class... T> void read(H &h, T &...t) {
    rd(h), read(t...);
}

void wt(const char c) {
    if (por == SZ)
        flush();
    obuf[por++] = c;
}
void wt(const string s) {
    for (char c : s)
        wt(c);
}
void wt(const char *s) {
    size_t len = strlen(s);
    for (size_t i = 0; i < len; i++)
        wt(s[i]);
}

template <typename T> void wt_integer(T x) {
    if (por > SZ - 100)
        flush();
    if (x < 0) {
        obuf[por++] = '-', x = -x;
    }
    int outi;
    for (outi = 96; x >= 10000; outi -= 4) {
        memcpy(out + outi, pre.num[x % 10000], 4);
        x /= 10000;
    }
    if (x >= 1000) {
        memcpy(obuf + por, pre.num[x], 4);
        por += 4;
    } else if (x >= 100) {
        memcpy(obuf + por, pre.num[x] + 1, 3);
        por += 3;
    } else if (x >= 10) {
        int q = (x * 103) >> 10;
        obuf[por] = q | '0';
        obuf[por + 1] = (x - q * 10) | '0';
        por += 2;
    } else
        obuf[por++] = x | '0';
    memcpy(obuf + por, out + outi + 4, 96 - outi);
    por += 96 - outi;
}

template <typename T> void wt_real(T x) {
    ostringstream oss;
    oss << fixed << setprecision(15) << double(x);
    string s = oss.str();
    wt(s);
}

void wt(int x) {
    wt_integer(x);
}
void wt(ll x) {
    wt_integer(x);
}
void wt(i128 x) {
    wt_integer(x);
}
void wt(uint x) {
    wt_integer(x);
}
void wt(ull x) {
    wt_integer(x);
}
void wt(u128 x) {
    wt_integer(x);
}
void wt(double x) {
    wt_real(x);
}
void wt(long double x) {
    wt_real(x);
}

template <class T, class U> void wt(const pair<T, U> val) {
    wt(val.first);
    wt(' ');
    wt(val.second);
}
template <size_t N = 0, typename T> void wt_tuple(const T t) {
    if constexpr (N < std::tuple_size<T>::value) {
        if constexpr (N > 0) {
            wt(' ');
        }
        const auto x = std::get<N>(t);
        wt(x);
        wt_tuple<N + 1>(t);
    }
}
template <class... T> void wt(tuple<T...> tpl) {
    wt_tuple(tpl);
}
template <class T, size_t S> void wt(const array<T, S> val) {
    auto n = val.size();
    for (size_t i = 0; i < n; i++) {
        if (i)
            wt(' ');
        wt(val[i]);
    }
}
template <class T> void wt(const vector<T> val) {
    auto n = val.size();
    for (size_t i = 0; i < n; i++) {
        if (i)
            wt(' ');
        wt(val[i]);
    }
}

void print() {
    wt('\n');
}
template <class Head, class... Tail> void print(Head &&head, Tail &&...tail) {
    wt(head);
    if (sizeof...(Tail))
        wt(' ');
    print(forward<Tail>(tail)...);
}
void __attribute__((destructor)) _d() {
    flush();
}
} // namespace fastio


using fastio::flush;
using fastio::print;
using fastio::read;

inline void first(bool i = true) {
    print(i ? "first" : "second");
}
inline void Alice(bool i = true) {
    print(i ? "Alice" : "Bob");
}
inline void Takahashi(bool i = true) {
    print(i ? "Takahashi" : "Aoki");
}
inline void yes(bool i = true) {
    print(i ? "yes" : "no");
}
inline void Yes(bool i = true) {
    print(i ? "Yes" : "No");
}
inline void No() {
    print("No");
}
inline void YES(bool i = true) {
    print(i ? "YES" : "NO");
}
inline void NO() {
    print("NO");
}
inline void Yay(bool i = true) {
    print(i ? "Yay!" : ":(");
}
inline void Possible(bool i = true) {
    print(i ? "Possible" : "Impossible");
}
inline void POSSIBLE(bool i = true) {
    print(i ? "POSSIBLE" : "IMPOSSIBLE");
}

/**
 * @brief Fast IO
 */

string CS = "()*+-&^|0123456789";
map<char,int> mp;

bool isValid(string S) {
    if (S == "") return false;
    int N = S.size();
    int Dep = 0;
    vector<int> OP;
    OP.push_back(-1);
    rep(i,0,N) {
        if (Dep < 0) return false;
        if (S[i] == '(') Dep++;
        else if (S[i] == ')') Dep--;
        else if (!isdigit(S[i])) {
            if (Dep == 0) {
                OP.push_back(i);
            }
        }
    }
    if (Dep != 0) return false;
    OP.push_back(N);
    if (OP.size() == 2) {
        if (S[0] == '(' && S[N-1] == ')') return isValid(S.substr(1,N-2));
        if (S[0] == '(' || S[N-1] == ')') return false;
        if (S[0] == '0') return false;
        return true;
    }
    rep(i,0,OP.size()-1) {
        int L = OP[i]+1, R = OP[i+1]-1;
        if (!isValid(S.substr(L,R-L+1))) return false;
    }
    return true;
}

ll Eval(string S) {
    int N = S.size();
    int Dep = 0, OPMAX = -1;
    vector<int> OP;
    OP.push_back(-1);
    rep(i,0,N) {
        if (S[i] == '(') Dep++;
        else if (S[i] == ')') Dep--;
        else if (!isdigit(S[i])) {
            if (Dep == 0) {
                OP.push_back(i);
                chmax(OPMAX, mp[S[i]]);
            }
        }
    }
    OP.push_back(N);
    if (OPMAX == -1) {
        if (S[0] == '(') return Eval(S.substr(1,N-2));
        return (ll)stoi(S);
    }
    vector<int> OP2;
    OP2.push_back(-1);
    rep(i,1,OP.size()-1) if (mp[S[OP[i]]] == OPMAX) OP2.push_back(OP[i]);
    OP2.push_back(N);
    ll Ret = Eval(S.substr(OP2[0]+1,OP2[1]-OP2[0]-1));
    rep(i,1,OP2.size()-1) {
        ll Ret2 = Eval(S.substr(OP2[i]+1,OP2[i+1]-OP2[i]-1));
        int ID = OP2[i];
        if (S[ID] == '*') Ret *= Ret2;
        if (S[ID] == '+') Ret += Ret2;
        if (S[ID] == '-') Ret -= Ret2;
        if (S[ID] == '&') Ret &= Ret2;
        if (S[ID] == '^') Ret ^= Ret2;
        if (S[ID] == '|') Ret |= Ret2;
    }
    return Ret;
}

ll Solve(int N, string S, bool B) {
    if (N == 0) {
        return Eval(S);
    }
    ll Ret = (B ? -INF : INF);
    int L = S.size();
    rep(i,0,L+1) {
        rep(j,0,CS.size()) {
            string T = S.substr(0,i) + CS[j] + S.substr(i,L-i);
            if (isValid(T)) {
                ll X = Solve(N-1,T,!B);
                B ? chmax(Ret,X) : chmin(Ret,X);
            }
        }
    }
    if (L >= 2) {
        rep(i,0,L) {
            string T = S.substr(0,i) + S.substr(i+1,L-i-1);
            if (isValid(T)) {
                ll X = Solve(N-1,T,!B);
                B ? chmax(Ret,X) : chmin(Ret,X);
            }
        }
    }
    return Ret;
}

int main() {
    mp['*'] = 0;
    mp['+'] = mp['-'] = 1;
    mp['&'] = 2;
    mp['^'] = 3;
    mp['|'] = 4;
while(1) {
    int N;
    string S;
    cin >> N >> S;
    if (N == 0) return 0;
    N = (N-1)%2+1;
    cout << Solve(N,S,true) << endl;
}
}
accuracy: 1
time_ms: 210
memory_kb: 3428
final_rank: 11

code_snippet: #include<bits/stdc++.h>
using namespace std;
using ll = long long;
using vll = vector<ll>;
#define rep(i,n) for(ll i=0;i<n;i++)
#define all(A) A.begin(),A.end()

ll calc(string S, ll n) {
    if (n == 0 && S[0] == '-') {
        S = "0" + S;
        return calc(S, 0);
    }
    // if(n==0)cout<<S<<endl;
    if (n == 5)return stoll(S);
    ll e = 0;
    if (n == 4)e = 1;
    else if (n == 2)e = -1;
    string T = "";
    ll SN = S.size();
    bool pr = 1;
    rep(i, SN) {
        if (S[i] == '*' && n == 4) {
            e *= calc(T, n + 1);
            T = "";
        }
        else if (T!=""&&T.back()!='*'&&(S[i] == '+' || S[i] == '-') && n == 3) {
            if (pr)e += calc(T, n + 1);
            else e -= calc(T, n + 1);
            pr = (S[i] == '+');
            T = "";
        }
        else if (S[i] == '&' && n == 2) {
            e &= calc(T, n + 1);
            T = "";
        }
        else if (S[i] == '^' && n == 1) {
            e ^= calc(T, n + 1);
            T = "";
        }
        else if (S[i] == '|' && n == 0) {
            e |= calc(T, n + 1);
            T = "";
        }
        else T.push_back(S[i]);
    }
    if (n == 4)e *= calc(T, n + 1);
    else if (n == 3) {
        if (pr)e += calc(T, n + 1);
        else e -= calc(T, n + 1);
    }
    else if (n == 2)e &= calc(T, n + 1);
    else if (n == 1)e ^= calc(T, n + 1);
    else e |= calc(T, n + 1);
    return e;
}
map<string, ll> MP;
ll eval(string S) {
    if (MP.count(S))return MP[S];
    ll SN = S.size();
    string T = "";
    rep(i, SN) {
        if (S[i] == '(') {
            ll cnt = 0;
            string R = "";
            for (ll j = i + 1; j < SN; j++) {
                if (S[j] == ')' && cnt == 0) {
                    T = T + to_string(eval(R));
                    i = j;
                    break;
                }
                else if (S[j] == '(') {
                    cnt++;
                }
                else if (S[j] == ')') {
                    cnt--;
                }
                R.push_back(S[j]);
            }
        }
        else T.push_back(S[i]);
    }
    ll res = calc(T, 0);
    MP[S] = res;
    // cout<<S<<" "<<res<<endl;
    return res;

}
bool is_dight(char C) { return '0' <= C && C <= '9'; };
string op = "*+-&^|";
bool is_op(char C) {
    for (auto p : op)if (C == p)return 1;
    return 0;
}

bool is_valid(string S){
    ll SN=S.size();
    rep(i,SN){
        if(S[i]=='0'){
            if(i==0)return 0;
            if(!is_dight(S[i-1]))return 0;
        }
    }
    return 1;
}

ll admax(string S, ll t = 1) {
    ll SN = S.size();
    ll an = -1e18;
    if (t == 0)an = 1e18;
    
    rep(i, SN) {
        //演算追加
        if (i != SN - 1 && is_dight(S[i]) && is_dight(S[i + 1])) {
            rep(j, 6) {
                string T = S.substr(0, i + 1) + op.substr(j, 1) + S.substr(i + 1, SN - i - 1);
                if(!is_valid(T))continue;
                if (t == 1)an = max(an, eval(T));
                else if (t == 0)an = min(an, eval(T));
                else if (t == 2)an = max(an, admax(T, 0));
            }
            if (S[i + 1] != '0') {
                string T = S.substr(0, i) + S.substr(i + 1, SN - i - 1);
                if(!is_valid(T))continue;
                if (t == 1)an = max(an, eval(T));
                else if (t == 0)an = min(an, eval(T));
                else if (t == 2)an = max(an, admax(T, 0));
            }
            {
                string T = S.substr(0, i + 1) + S.substr(i + 2, SN - i - 1);
                if(!is_valid(T))continue;
                if (t == 1)an = max(an, eval(T));
                else if (t == 0)an = min(an, eval(T));
                else if (t == 2)an = max(an, admax(T, 0));
            }
        }
        //前後に足す
        if (is_dight(S[i])) {
            rep(j, 10) {
                string T = S.substr(0, i + 1) + to_string(j) + S.substr(i + 1, SN - i - 1);
                if(is_valid(T)){
                    if (t == 1)an = max(an, eval(T));
                    else if (t == 0)an = min(an, eval(T));
                    else if (t == 2)an = max(an, admax(T, 0));
                }

                if (j == 0 && (i == 0 || !is_dight(S[i - 1])))continue;
                T = S.substr(0, i) + to_string(j) + S.substr(i, SN - i);
                if(!is_valid(T))continue;
                if (t == 1)an = max(an, eval(T));
                else if (t == 0)an = min(an, eval(T));
                else if (t == 2)an = max(an, admax(T, 0));
            }
        }
        //演算除去
        else if (is_op(S[i])&&is_dight(S[i-1])&&is_dight(S[i+1])) {
            string T = S.substr(0, i) + S.substr(i + 1, SN - i - 1);
            if(!is_valid(T))continue;
            if (t == 1)an = max(an, eval(T));
            else if (t == 0)an = min(an, eval(T));
            else if (t == 2)an = max(an, admax(T, 0));
        }
    }
    // cout<<S<<" "<<an<<" "<<t<<endl;
    return an;
}

void solve(ll N, string S) {
    if (N % 2 == 1) {
        cout << admax(S, 1) << endl;
        return;
    }
    else {
        cout << admax(S, 2) << endl;
        return;
    }
    cout << "MADA" << endl;
}

int main() {
    ll N;
    string S;
    while (cin >> N >> S, S != "#")solve(N, S);
}
accuracy: 1
time_ms: 310
memory_kb: 19000
final_rank: 16

code_snippet: #include<bits/stdc++.h>
using namespace std;
using ll = long long;
using vll = vector<ll>;
#define rep(i,n) for(ll i=0;i<n;i++)
#define all(A) A.begin(),A.end()

ll calc(string S, ll n) {
    if (n == 0 && S[0] == '-') {
        S = "0" + S;
        return calc(S, 0);
    }
    // if(n==0)cout<<S<<endl;
    if (n == 5)return stoll(S);
    ll e = 0;
    if (n == 4)e = 1;
    else if (n == 2)e = -1;
    string T = "";
    ll SN = S.size();
    bool pr = 1;
    rep(i, SN) {
        if (S[i] == '*' && n == 4) {
            e *= calc(T, n + 1);
            T = "";
        }
        else if (T!=""&&(S[i] == '+' || S[i] == '-') && n == 3) {
            if (pr)e += calc(T, n + 1);
            else e -= calc(T, n + 1);
            pr = (S[i] == '+');
            T = "";
        }
        else if (S[i] == '&' && n == 2) {
            e &= calc(T, n + 1);
            T = "";
        }
        else if (S[i] == '^' && n == 1) {
            e ^= calc(T, n + 1);
            T = "";
        }
        else if (S[i] == '|' && n == 0) {
            e |= calc(T, n + 1);
            T = "";
        }
        else T.push_back(S[i]);
    }
    if (n == 4)e *= calc(T, n + 1);
    else if (n == 3) {
        if (pr)e += calc(T, n + 1);
        else e -= calc(T, n + 1);
    }
    else if (n == 2)e &= calc(T, n + 1);
    else if (n == 1)e ^= calc(T, n + 1);
    else e |= calc(T, n + 1);
    return e;
}
map<string, ll> MP;
ll eval(string S) {
    if (MP.count(S))return MP[S];
    ll SN = S.size();
    string T = "";
    rep(i, SN) {
        if (S[i] == '(') {
            ll cnt = 0;
            string R = "";
            for (ll j = i + 1; j < SN; j++) {
                if (S[j] == ')' && cnt == 0) {
                    T = T + to_string(eval(R));
                    i = j;
                    break;
                }
                else if (S[j] == '(') {
                    cnt++;
                }
                else if (S[j] == ')') {
                    cnt--;
                }
                R.push_back(S[j]);
            }
        }
        else T.push_back(S[i]);
    }
    ll res = calc(T, 0);
    MP[S] = res;
    // cout<<S<<" "<<res<<endl;
    return res;

}
bool is_dight(char C) { return '0' <= C && C <= '9'; };
string op = "*+-&^|";
bool is_op(char C) {
    for (auto p : op)if (C == p)return 1;
    return 0;
}

bool is_valid(string S){
    ll SN=S.size();
    rep(i,SN){
        if(S[i]=='0'){
            if(i==0)return 0;
            if(!is_dight(S[i-1]))return 0;
        }
    }
    return 1;
}

ll admax(string S, ll t = 1) {
    ll SN = S.size();
    ll an = -1e18;
    if (t == 0)an = 1e18;
    
    rep(i, SN) {
        //演算追加
        if (i != SN - 1 && is_dight(S[i]) && is_dight(S[i + 1])) {
            rep(j, 6) {
                string T = S.substr(0, i + 1) + op.substr(j, 1) + S.substr(i + 1, SN - i - 1);
                if(!is_valid(T))continue;
                if (t == 1)an = max(an, eval(T));
                else if (t == 0)an = min(an, eval(T));
                else if (t == 2)an = max(an, admax(T, 0));
            }
            if (S[i + 1] != '0') {
                string T = S.substr(0, i) + S.substr(i + 1, SN - i - 1);
                if(!is_valid(T))continue;
                if (t == 1)an = max(an, eval(T));
                else if (t == 0)an = min(an, eval(T));
                else if (t == 2)an = max(an, admax(T, 0));
            }
            {
                string T = S.substr(0, i + 1) + S.substr(i + 2, SN - i - 1);
                if(!is_valid(T))continue;
                if (t == 1)an = max(an, eval(T));
                else if (t == 0)an = min(an, eval(T));
                else if (t == 2)an = max(an, admax(T, 0));
            }
        }
        //前後に足す
        if (is_dight(S[i])) {
            rep(j, 10) {
                string T = S.substr(0, i + 1) + to_string(j) + S.substr(i + 1, SN - i - 1);
                if(is_valid(T)){
                    if (t == 1)an = max(an, eval(T));
                    else if (t == 0)an = min(an, eval(T));
                    else if (t == 2)an = max(an, admax(T, 0));
                }

                if (j == 0 && (i == 0 || !is_dight(S[i - 1])))continue;
                T = S.substr(0, i) + to_string(j) + S.substr(i, SN - i);
                if(!is_valid(T))continue;
                if (t == 1)an = max(an, eval(T));
                else if (t == 0)an = min(an, eval(T));
                else if (t == 2)an = max(an, admax(T, 0));
            }
        }
        //演算除去
        else if (is_op(S[i])&&is_dight(S[i-1])&&is_dight(S[i+1])) {
            string T = S.substr(0, i) + S.substr(i + 1, SN - i - 1);
            if(!is_valid(T))continue;
            if (t == 1)an = max(an, eval(T));
            else if (t == 0)an = min(an, eval(T));
            else if (t == 2)an = max(an, admax(T, 0));
        }
    }
    // cout<<S<<" "<<an<<" "<<t<<endl;
    return an;
}

void solve(ll N, string S) {
    if (N % 2 == 1) {
        cout << admax(S, 1) << endl;
        return;
    }
    else {
        cout << admax(S, 2) << endl;
        return;
    }
    cout << "MADA" << endl;
}

int main() {
    ll N;
    string S;
    while (cin >> N >> S, S != "#")solve(N, S);
}
accuracy: 0.5
time_ms: 300
memory_kb: 18028
final_rank: 20

code_snippet: #line 2 "cp-library/src/cp-template.hpp"
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
using uint = unsigned int;
using ull  = unsigned long long;
using i32 = int;
using u32 = unsigned int;
using i64 = long long;
using u64 = unsigned long long;
using i128 = __int128_t;
template < class T > bool chmin(T& a, T b) { if(a > b) { a = b; return true; } return false; }
template < class T > bool chmax(T& a, T b) { if(a < b) { a = b; return true; } return false; }
template < class T, class U > T ceil (T x, U y) { return (x > 0 ? (x + y - 1) / y :           x / y); }
template < class T, class U > T floor(T x, U y) { return (x > 0 ?           x / y : (x - y + 1) / y); }
int popcnt(i32 x) { return __builtin_popcount(x); }
int popcnt(u32 x) { return __builtin_popcount(x); }
int popcnt(i64 x) { return __builtin_popcountll(x); }
int popcnt(u64 x) { return __builtin_popcountll(x); }

#line 2 "cp-library/src/utility/rep_itr.hpp"
template < class T > struct itr_rep {
    T i, d;
    constexpr itr_rep(const T i) noexcept : i(i), d(1) {}
    constexpr itr_rep(const T i, const T d) noexcept : i(i), d(d) {}
    void operator++() noexcept { i += d; }
    constexpr int operator*() const noexcept { return i; }
    constexpr bool operator!=(const itr_rep x) const noexcept { return d > 0 ? i < x.i : i > x.i; }
};

template < class T > struct rep {
    const itr_rep< T > s, t;
    constexpr rep(const T t) noexcept : s(0), t(t) {}
    constexpr rep(const T s, const T t) noexcept : s(s), t(t) {}
    constexpr rep(const T s, const T t, const T d) noexcept : s(s, d), t(t, d) {}
    constexpr auto begin() const noexcept { return s; }
    constexpr auto end  () const noexcept { return t; }
};

template < class T > struct revrep {
    const itr_rep < T > s, t;
    constexpr revrep(const T t) noexcept : s(t - 1, -1), t(-1, -1) {}
    constexpr revrep(const T s, const T t) noexcept : s(t - 1, -1), t(s - 1, -1) {}
    constexpr revrep(const T s, const T t, const T d) noexcept : s(t - 1, -d), t(s - 1, -d) {}
    constexpr auto begin() const noexcept { return s; }
    constexpr auto end  () const noexcept { return t; }
};
#line 3 "cp-library/src/utility/io.hpp"

/* 128bit integer */
istream& operator>>(istream& is, i128& x) {
    std::string s; is >> s;
    int pm = (s[0] == '-');
    x = 0;
    for(int i : rep(pm, int(s.size()))) x = x * 10 + (s[i] - '0');
    if(pm) x *= -1;
    return is;
}
ostream& operator<<(ostream& os, const i128& x) {
    if(x == 0) return os << '0';
    i128 y = x;
    if(y < 0) { os << '-'; y *= -1; }
    std::vector<int> ny;
    while(y > 0) { ny.push_back(y % 10); y /= 10; }
    for(int i : revrep(ny.size())) os << ny[i];
    return os;
}

template < class S, class T > istream& operator>>(istream& is,       std::pair< S, T >& x) { is >> x.first        >> x.second; return is; }
template < class S, class T > ostream& operator<<(ostream& os, const std::pair< S, T >& x) { os << x.first << " " << x.second; return os; }

namespace scanner {
    struct sca {
        template < class T > operator T() {
            T s; std::cin >> s; return s;
        }
    };
    struct vec {
        int n;
        vec(int n) : n(n) {}
        template < class T > operator std::vector< T >() {
            std::vector< T > v(n);
            for(T& x : v) std::cin >> x;
            return v;
        }
    };
    struct mat {
        int h, w;
        mat(int h, int w) : h(h), w(w) {}
        template < class T > operator std::vector< std::vector< T > >() {
            std::vector m(h, std::vector< T >(w));
            for(std::vector< T >& v : m) for(T& x : v) std::cin >> x;
            return m;
        }
    };
    struct speedup {
        speedup() {
            std::cin.tie(0);
            std::ios::sync_with_stdio(0);
        }
    } speedup_instance;
}
scanner::sca in() { return scanner::sca(); }
scanner::vec in(int n) { return scanner::vec(n); }
scanner::mat in(int h, int w) { return scanner::mat(h, w); }

namespace printer {
    void precision(int d) { std::cout << std::fixed << std::setprecision(d); }
    void flush() { std::cout.flush(); }
}

template < class T >
ostream& operator<<(ostream& os, const std::vector< T > a) {
    int n = a.size();
    for(int i : rep(n)) { os << a[i]; if(i != n - 1) os << ' '; }
    return os;
}

int print() { std::cout << '\n'; return 0; }
template < class head, class... tail > int print(head&& h, tail&&... t) {
    std::cout << h; if(sizeof...(tail)) std::cout << ' ';
    return print(std::forward<tail>(t)...);
}
template < class T > int print_n(const std::vector< T > a) {
    int n = a.size();
    for(int i : rep(n)) std::cout << a[i] << "\n";
    return 0;
}


#line 2 "cp-library/src/utility/key_val.hpp"

template < class K, class V >
struct key_val {
    K key; V val;
    key_val() {}
    key_val(K key, V val) : key(key), val(val) {}
    template < std::size_t Index >
    std::tuple_element_t< Index, key_val >& get() {
        if constexpr (Index == 0) return key;
        if constexpr (Index == 1) return val;
    }
};

namespace std {

template < class K, class V > struct tuple_size < key_val< K, V > > : integral_constant< size_t, 2 > {};
template < class K, class V > struct tuple_element < 0, key_val< K, V > > { using type = K; };
template < class K, class V > struct tuple_element < 1, key_val< K, V > > { using type = V; };

}
#line 2 "cp-library/src/utility/vec_op.hpp"
template < class T > key_val< int, T > max_of(const vector< T >& a) {
    int i = std::max_element(a.begin(), a.end()) - a.begin();
    return {i, a[i]};
}
template < class T > key_val< int, T > min_of(const vector< T >& a) {
    int i = std::min_element(a.begin(), a.end()) - a.begin();
    return {i, a[i]};
}
template < class S, class T > S sum_of(const vector< T >& a) {
    S sum = 0;
    for(const T x : a) sum += x;
    return sum;
}
template < class S, class T > vector< S > freq_of(const vector< T >& a, T L, T R) {
    vector< S > res(R - L, S(0));
    for(const T x : a) res[x - L] += 1;
    return res;
}
template < class S, class T > struct prefix_sum {
    vector< S > s;
    prefix_sum(const vector< T >& a) : s(a) {
        s.insert(s.begin(), S(0));
        for(int i : rep(a.size())) s[i + 1] += s[i];
    }
    // [L, R)
    S sum(int L, int R) { return s[R] - s[L]; }
};
#line 3 "cp-library/src/utility/heap.hpp"

template < class T > using heap_min = std::priority_queue< T, std::vector< T >, std::greater< T > >;
template < class T > using heap_max = std::priority_queue< T, std::vector< T >, std::less< T > >;

#line 27 "cp-library/src/cp-template.hpp"

#line 1 "cp-library/src/algorithm/bin_search.hpp"
template < class T, class F >
T bin_search(T ok, T ng, F f) {
    while(abs(ng - ok) > 1) {
        T mid = (ok + ng) / 2;
        (f(mid) ? ok : ng) = mid;
    }
    return ok;
}

template < class T, class F >
T bin_search_real(T ok, T ng, F f, int step = 80) {
    while(step--) {
        T mid = (ok + ng) / 2;
        (f(mid) ? ok : ng) = mid;
    }
    return ok;
}
#line 2 "cp-library/src/algorithm/argsort.hpp"

template < class T > std::vector< int > argsort(const std::vector< T > &a) {
    std::vector< int > ids((int)a.size());
    std::iota(ids.begin(), ids.end(), 0);
    std::sort(ids.begin(), ids.end(), [&](int i, int j) {
        return a[i] < a[j] || (a[i] == a[j] && i < j);
    });
    return ids;
}
#line 1 "macro.hpp"
namespace macro {

using size_type = int;
template < class container > void  sort(container& a) { std::sort(std:: begin(a), std:: end(a)); }
template < class container > void rsort(container& a) { std::sort(std::rbegin(a), std::rend(a)); }
template < class container > void reverse(container& a) { std::reverse(std::begin(a), std::end(a)); }
template < class container > void unique(container& a) {
    std::sort(std::begin(a), std::end(a));
    a.erase(std::unique(std::begin(a), std::end(a)), std::end(a));
}
template < class container > container  sorted(const container& a) { container b = a;  sort(b); return std::move(b); }
template < class container > container rsorted(const container& a) { container b = a; rsort(b); return std::move(b); }
template < class container, class compare > void sort(container& a, const compare& cmp) { std::sort(std::begin(a), std::end(a), cmp); }
template < class container, class compare > container sorted(const container& a, const compare& cmp) { container b = a; sort(b, cmp); return std::move(b); }
template < class container, class value > size_type lower_bound(const container& a, const value& x) { return std::lower_bound(std::begin(a), std::end(a), x) - std::begin(a); }
template < class container, class value > size_type upper_bound(const container& a, const value& x) { return std::upper_bound(std::begin(a), std::end(a), x) - std::begin(a); }

const std::vector<std::pair<size_type, size_type>> dir4 = { {+1,  0}, {-1,  0}, { 0, +1}, { 0, -1} };
const std::vector<std::pair<size_type, size_type>> dir8 = { {-1, -1}, {-1,  0}, {-1, +1}, { 0, -1}, { 0, +1}, {+1, -1}, {+1,  0}, {+1, +1} };

#ifdef _DEBUG
#define debug(x) std::cout << "[" << __LINE__ << "] " << #x << ": " << x << std::endl
#else
#define debug(x)
#endif

template < class container > void concat(container& a, const container& b) {
    a.insert(std::end(a), std::begin(b), std::end(b));
}
std::vector<size_type> iota(const size_type n) {
    std::vector<size_type> I(n);
    std::iota(std::begin(I), std::end(I), 0);
    return I;
}
template < class container > std::vector<size_type> sort_idx(const container& a) {
    const size_type n = a.size();
    std::vector<size_type> I = iota(n);
    std::sort(std::begin(I), std::end(I), [&](size_type i, size_type j) { return a[i] < a[j] or (a[i] == a[j] and i < j); });
    return I;
}
template < class container, class compare > std::vector<size_type> sort_idx(const container& a, const compare& cmp) {
    const size_type n = a.size();
    std::vector<size_type> I = iota(n);
    std::sort(std::begin(I), std::end(I), [&](size_type i, size_type j) { return cmp(a[i], a[j]) or (a[i] == a[j] and i < j); });
    return std::move(I);
}

struct grid {
    using size_type = int;
    size_type H, W;
    grid(const size_type H, const size_type W) : H(H), W(W) {}
    bool contains(const size_type i, const size_type j) {
        return 0 <= i and i < H and 0 <= j and j < W;
    }
};

using f64 = long double;

template < class T > vector< T >& operator++(vector< T >& a) { for(T& x : a) x++; return a; }
template < class T > vector< T >& operator--(vector< T >& a) { for(T& x : a) x--; return a; }
template < class T > vector< T >  operator++(vector< T >& a, signed) { vector< T > res = a; for(T& x : a) x++; return res; }
template < class T > vector< T >  operator--(vector< T >& a, signed) { vector< T > res = a; for(T& x : a) x--; return res; }

} // namespace macro

using namespace macro;
#line 3 "A.cpp"

bool valid;
pair<bool, int> f(string);
int OR (int&, string&);
int XOR(int&, string&);
int AND(int&, string&);
int PM (int&, string&);
int MUL(int&, string&);
int fac(int&, string&);
int num(int&, string&);
pair<bool, int> f(string s) {
    int i = 0;
    valid = true;
    int ans = OR(i, s);
    valid &= i == s.size();
    return {valid, ans};
}
int OR(int& i, string& s) {
    int ans = XOR(i, s);
    while(s[i] == '|') { i++; ans |= XOR(i, s); }
    return ans;
}
int XOR(int& i, string& s) {
    int ans = AND(i, s);
    while(s[i] == '^') { i++; ans ^= AND(i, s); }
    return ans;
}
int AND(int& i, string& s) {
    int ans = PM(i, s);
    while(s[i] == '&') { i++; ans &= PM(i, s); }
    return ans;
}
int PM(int& i, string& s) {
    int ans = MUL(i, s);
    while(s[i] == '+' || s[i] == '-') {
        if(s[i] == '+') {
            i++;
            ans += MUL(i, s);
        } else {
            i++;
            ans -= MUL(i, s);
        }
    }
    return ans;
}
int MUL(int& i, string& s) {
    int ans = fac(i, s);
    while(s[i] == '*') { i++; ans *= fac(i, s); }
    return ans;
}
int fac(int& i, string& s) {
    if(s[i] == '(') {
        i++;
        int ans = OR(i, s);
        if(s[i] != ')') valid = false;
        i++;
        return ans;
    } else {
        return num(i, s);
    }
}
int num(int& i, string& s) {
    if(std::isdigit(s[i]) and s[i] != '0') {
        int ans = 0;
        while(std::isdigit(s[i])) { ans = ans * 10 + (s[i] - '0'); i++; }
        return ans;
    } else {
        valid = false;
        i++;
        return 0;
    }
}

vector<pair<string,int>> cand(string s) {
    vector<pair<string,int>> res;
    const int n = s.size();
    for(int i : rep(n - 1)) {
        if(isdigit(s[i]) and isdigit(s[i + 1])) {
            for(char op : "*+-&^|"s) {
                s.insert(s.begin() + i + 1, op);
                auto [isvalid, score] = f(s);
                if(isvalid) res.push_back({s, score});
                s.erase(s.begin() + i + 1);
            }
        }
    }
    for(int i : rep(n + 1)) {
        if((0 <= i - 1 and isdigit(s[i - 1])) or (i < n and isdigit(s[i]))) {
            for(char d = '0'; d <= '9'; d++) {
                s.insert(s.begin() + i, d);
                auto [isvalid, score] = f(s);
                if(isvalid) res.push_back({s, score});
                s.erase(s.begin() + i);
            }
        }
    }
    for(int i : rep(n)) {
        string t = s.substr(0, i) + s.substr(i + 1, s.size());
        auto [isvalid, score] = f(t);
        if(isvalid) res.push_back({t, score});
    }
    return res;
}

int ODD(string s) {
    int ans = INT_MIN;
    const int n = s.size();
    for(auto [s2, score] : cand(s)) chmax(ans, score);
    return ans;
}

int EVEN(string s) {
    vector<pair<string,int>> cand_s = cand(s);
    int ans = INT_MIN;
    for(auto [t, _] : cand_s) {
        vector<pair<string,int>> cand_t = cand(t);
        int mi = INT_MAX;
        for(auto [u, score] : cand_t) chmin(mi, score);
        chmax(ans, mi);
    }
    return ans;
}

int main() {
    while(true) {
        int n = in(); string s = in();
        if(make_pair(n, s) == make_pair(0, "#"s)) return 0;
        if(n % 2 == 1) {
            print(ODD(s));
        } else {
            print(EVEN(s));
        }
    }
}
accuracy: 1
time_ms: 20
memory_kb: 3392
final_rank: 1

code_snippet: #include <bits/stdc++.h>

constexpr long long INF = std::numeric_limits<long long>::max();

constexpr int W = 16;
const std::vector<char> ALPHABET = {
    /* '(', ')', */ '*', '+', '-', '&', '^', '|', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
const std::vector<char> OPE = {'*', '+', '-', '&', '^', '|'};
const std::vector<char> DIGIT = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};

const std::vector<std::vector<char>> PRIORITY_OPE = {{'|'}, {'^'}, {'&'}, {'+', '-'}, {'*'}};

bool contain(const std::vector<char>& set, char c) {
    return std::find(set.begin(), set.end(), c) != set.end();
}

long long op(long long lhs, long long rhs, char c) {
    if (c == '*')
        return lhs * rhs;
    else if (c == '+')
        return lhs + rhs;
    else if (c == '-')
        return lhs - rhs;
    else if (c == '&')
        return lhs & rhs;
    else if (c == '^')
        return lhs ^ rhs;
    else
        return lhs | rhs;
}

class ParseError {};

struct Parser {
    using CopyIter = std::string::const_iterator;
    using Iter = CopyIter&;
    std::string line;
    Parser(std::string line): line(line) {}

    void skip(Iter it, char c) {
        if (*it != c) {
            throw ParseError();
        }
        ++it;
    }

    std::pair<bool, long long> parse() {
        try {
            auto it = line.cbegin();
            auto res = expr(it, 0);
            if (it == line.end()) return {true, res};
            return {false, -1};
        } catch (ParseError) {
            return {false, -1};
        }
    }

    long long expr(Iter it, int level) {
        if (level == (int)PRIORITY_OPE.size()) {
            return term(it);
        }
        auto res = expr(it, level + 1);

        while (it != line.end() && contain(PRIORITY_OPE[level], *it)) {
            char c = *it;
            skip(it, c);
            res = op(res, expr(it, level + 1), c);
        }

        return res;
    }

    long long term(Iter it) {
        if (it == line.end()) {
            throw ParseError();
        }
        if (*it == '(') {
            skip(it, '(');
            auto res = expr(it, 0);
            skip(it, ')');
            return res;
        } else {
            return positive_number(it);
        }
    }

    long long positive_number(Iter it) {
        if (it == line.end() || !std::isdigit(*it) || *it == '0') {
            throw ParseError();
        }

        long long res = 0;
        while (it != line.end() && std::isdigit(*it)) {
            auto c = *it;
            skip(it, c);
            res = 10 * res + c - '0';
        }
        return res;
    }
};

void parser_test() {
    std::string test1 = "(1+2)+3";
    std::string test2 = "1+2*3+4";
    std::string test3 = "(1+2)*(3+4)";
    std::string test4 = "1^2&4|8";
    std::string test5 = "123**123";
    std::string test6 = "0&2134";
    std::string test7 = "0101&2134";

    auto print = [](std::pair<bool, long long> p) {
        std::cerr << p.first << ' ' << p.second << std::endl;
    };

    {
        Parser parser(test1);
        std::cerr << 6 << ' ';
        print(parser.parse());
    }
    {
        Parser parser(test2);
        std::cerr << 11 << ' ';
        print(parser.parse());
    }
    {
        Parser parser(test3);
        std::cerr << 21 << ' ';
        print(parser.parse());
    }
    {
        Parser parser(test4);
        std::cerr << 9 << ' ';
        print(parser.parse());
    }
    {
        Parser parser(test5);
        std::cerr << 9 << ' ';
        print(parser.parse());
    }
    {
        Parser parser(test6);
        std::cerr << 9 << ' ';
        print(parser.parse());
    }
    {
        Parser parser(test7);
        std::cerr << 9 << ' ';
        print(parser.parse());
    }
}

long long dfs(std::string formula, int n, bool first) {
    if (n == 0) {
        Parser parser(formula);
        auto [ok, val] = parser.parse();
        return val;
    }

    long long ans = (first ? -1 : 1) * INF;

    for (int i = 0; i < (int)formula.size(); i++) {
        auto temp = formula;
        temp.erase(temp.begin() + i);
        Parser parser(temp);
        auto [ok, val] = parser.parse();
        if (!ok) continue;
        if (first) {
            ans = std::max(ans, dfs(temp, n - 1, first ^ 1));
        } else {
            ans = std::min(ans, dfs(temp, n - 1, first ^ 1));
        }
    }

    for (int i = 0; i <= (int)formula.size(); i++) {
        for (auto c: ALPHABET) {
            auto temp = formula;
            temp.insert(i, 1, c);
            Parser parser(temp);
            auto [ok, val] = parser.parse();
            if (!ok) continue;
            if (first) {
                ans = std::max(ans, dfs(temp, n - 1, first ^ 1));
            } else {
                ans = std::min(ans, dfs(temp, n - 1, first ^ 1));
            }
        }
    }

    return ans;
}

int main() {
    while (true) {
        int n;
        std::string s;
        std::cin >> n >> s;
        if (n == 0 && s == "#") break;

        std::cout << dfs(s, (n % 2 == 0 ? 2 : 1), true) << std::endl;
    }
}
accuracy: 1
time_ms: 380
memory_kb: 3420
final_rank: 14

code_snippet: #include "bits/stdc++.h"
using namespace std;
using namespace std::chrono;
typedef long long int llint;
typedef long double lldo;
#define mp make_pair
#define mt make_tuple
#define pub push_back
#define puf push_front
#define pob pop_back
#define pof pop_front
#define fir first
#define sec second
#define res resize
#define ins insert
#define era erase
#define REP(i, n) for(int i = 0;i < (n);i++)
/*cout<<fixed<<setprecision(20);cin.tie(0);ios::sync_with_stdio(false);*/
const int mod=1000000007;
const llint inf=2.19e15+1;
const long double pai=3.141592653589793238462643383279502884197;
const long double eps=1e-10;
template <class T,class U>bool chmin(T& a,U b){if(a>b){a=b;return true;}return false;}
template <class T,class U>bool chmax(T& a,U b){if(a<b){a=b;return true;}return false;}
llint gcd(llint a,llint b){if(a%b==0){return b;}else return gcd(b,a%b);}
llint lcm(llint a,llint b){if(a==0){return b;}return a/gcd(a,b)*b;}
template<class T> void SO(T& ve){sort(ve.begin(),ve.end());}
template<class T> void REV(T& ve){reverse(ve.begin(),ve.end());}
template<class T>int LBI(const vector<T>&ar,T in){return lower_bound(ar.begin(),ar.end(),in)-ar.begin();}
template<class T>int UBI(const vector<T>&ar,T in){return upper_bound(ar.begin(),ar.end(),in)-ar.begin();}
//5回=3回=1回
pair<bool,llint> getval(string S){
	//validかどうか、およびその値
	//( 数字 ) 二項演算 ( 数字 )...
	//cerr<<S<<endl;
	
	vector<pair<llint,int>>siki;
	//数字 ,0 または、 演算子,優先順位
	int zyo=0,i,j;
	int kakko=0;
	for(char c:S){
		
		if(zyo==0){
			if(c=='('){kakko++;}
			else{siki.pub(mp(0LL,0));zyo++;}
		}
		
		if(zyo==1){
			if('0'<=c&&c<='9'){
				if(siki.back().fir==0&&c=='0'){return mp(false,0LL);}
				siki.back().fir*=10;
				siki.back().fir+=c-'0';
			}else{
				if(siki.back().fir==0){return mp(false,0LL);}
				zyo++;
			}
		}
		
		if(zyo==2){
			if(c==')'){kakko--;if(kakko<0){return mp(false,0LL);}}
			else{zyo++;}
		}
		
		if(zyo==3){
			if(c=='*'){siki.pub(mp((llint)c,kakko*10+5));}
			else if(c=='+'){siki.pub(mp((llint)c,kakko*10+4));}
			else if(c=='-'){siki.pub(mp((llint)c,kakko*10+4));}
			else if(c=='&'){siki.pub(mp((llint)c,kakko*10+3));}
			else if(c=='^'){siki.pub(mp((llint)c,kakko*10+2));}
			else if(c=='|'){siki.pub(mp((llint)c,kakko*10+1));}
			else{return mp(false,0LL);}
			
			zyo=0;
		}
	}
	
	if(zyo==0||kakko>0){return mp(false,0LL);}
	
	//式を計算する
	
	while(siki.size()>1){
		int enbas=-1;
		int enyu=-1;
		for(i=1;i<siki.size();i+=2){
			if(chmax(enyu,siki[i].sec)){enbas=i;}
		}
		//enbasに沿って演算する
		llint X,A,B;
		A=siki[enbas-1].fir;
		B=siki[enbas+1].fir;
		if(siki[enbas].fir=='*'){X=A*B;}
		if(siki[enbas].fir=='+'){X=A+B;}
		if(siki[enbas].fir=='-'){X=A-B;}
		if(siki[enbas].fir=='&'){X=A&B;}
		if(siki[enbas].fir=='^'){X=A^B;}
		if(siki[enbas].fir=='|'){X=A|B;}
		siki[enbas-1].fir=X;
		siki.erase(siki.begin()+enbas,siki.begin()+enbas+2);
	}
	//cerr<<"ret "<<siki[0].fir<<endl;
	return mp(true,siki[0].fir);
}
llint solve(string S,int n,int fuka){
	//fuka=1なら最大化、2なら最小化
	string mozi="0123456789+-*&^|";
	int i,j;
	llint ans;
	if(fuka==1){ans=-inf;}
	else{ans=inf;}
	for(i=0;i<S.size();i++){
		string T=S;
		T.erase(T.begin()+i);
		auto aaa=getval(T);
		if(aaa.fir){
			llint kaz;
			if(n==1){kaz=aaa.sec;}
			else{kaz=solve(T,n-1,3-fuka);}
			
			if(fuka==1){chmax(ans,kaz);}
			else{chmin(ans,kaz);}
		}
	}
	for(i=0;i<=S.size();i++){
		for(j=0;j<16;j++){
			string T=S;
			T.insert(T.begin()+i,mozi[j]);
			auto aaa=getval(T);
			if(aaa.fir){
				llint kaz;
				if(n==1){kaz=aaa.sec;}
				else{kaz=solve(T,n-1,3-fuka);}
				
				if(fuka==1){chmax(ans,kaz);}
				else{chmin(ans,kaz);}
			}
		}
	}
	//cerr<<"ans="<<ans<<" "<<n<<"  "<<S<<endl;
	return ans;
	
}
int main(void){
	while(true){
		llint n;string str;
		cin>>n>>str;
		if(n==0){break;}
		if(n%2==1){cout<<solve(str,1,1)<<endl;}
		else{cout<<solve(str,2,1)<<endl;}
	}
	
	return 0;
}
accuracy: 1
time_ms: 40
memory_kb: 3336
final_rank: 4

code_snippet: #include <iostream>
#include <algorithm>
#include <map>
#include <set>
#include <queue>
#include <bitset>
#include <climits>
#include <string>
#include <cmath>
#include <bitset>
#include <complex>
#include <functional>
#include <ctime>
#include <cassert>
#include <fstream>
#include <stack>
#include <random>
#include <iomanip>
#include <time.h>
#include <list>
#include <unordered_map>

#include <algorithm>
#include <array>

using namespace std;
typedef long long ll;
typedef long double dd;
typedef unsigned long long ull;
typedef vector<ll> vl;
typedef vector<dd> vd;
typedef vector<vector<ll>> vvl;
typedef vector<vector<dd>> vvd;
//#define i_7 (ll)(1E9+7)
#define i_7 998244353
#define i_5 i_7-2
ll mod(ll a){
    ll c=a%i_7;
    if(c>=0)return c;
    return c+i_7;
}
typedef pair<ll,ll> l_l;
typedef pair<dd,dd> d_d;
ll inf=(ll)1E18;
#define rep(i,l,r) for(ll i=l;i<=r;i++)
#define pb push_back
ll max(ll a,ll b){if(a<b)return b;else return a;}
ll min(ll a,ll b){if(a>b)return b;else return a;}
dd EPS=1E-9;
dd PI=acos(-1);
#define endl "\n"
#define fastio ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);


bool valid;
ll exp(string &s, ll &cur, ll now_op);

bool is_op(char c, ll op_num){
    vector<string> ops={
        "|",
        "^",
        "&",
        "+-",
        "*"
    };
    rep(i,0,(ll)ops[op_num].size()-1){
        if(c == ops[op_num][i])return true;
    }
    return false;
}

ll calc(ll x, ll y, char op){
    if(op == '|'){
        return x|y;
    }else if(op == '^'){
        return x^y;
    }else if(op == '&'){
        return x&y;
    }else if(op == '+'){
        return x+y;
    }else if(op == '-'){
        return x-y;
    }else if(op == '*'){
        return x*y;
    }else{
        assert(false);
        return 0;
    }
}

ll Number(string &s, ll &cur){
    ll res=0;
    if(!isdigit(s[cur]) || s[cur] == '0'){
        valid = false;
        return 0;
    }
    while(isdigit(s[cur])){
        res *= 10;
        res += s[cur] - '0';
        cur++;
    }
    return res;
}

ll exp(string &s, ll &cur, ll now_op){
    if(!valid)return 0;
    if(now_op == 5){
        //(exp0) or number
        if(s[cur] == '('){
            cur++;
            ll res = exp(s, cur, 0);
            if(s[cur] != ')'){
                valid=false;
                return 0;
            }
            cur++;
            return res;
        }else{
            ll res = Number(s, cur);
            if(!valid)return 0;
            return res;
        }
    }
    ll res = exp(s, cur, now_op+1);
    while(cur < (ll)s.size() && is_op(s[cur], now_op)){
        char op = s[cur];
        cur++;
        ll tmp = exp(s, cur, now_op+1);
        res = calc(res, tmp, op);
    }
    return res;
}

ll dfs(string &s, ll now, ll n){
    if(now == n){
        ll cur=0;
        valid=true;
        ll res = exp(s, cur, 0);
        assert(valid);
        assert(cur==(ll)s.size());
        return res;
    }
    vl v;
    //書き換えした先の値をvに突っ込む
    rep(i,0,(ll)s.size()-1){
        //s[i]を削除
        string t;
        rep(j,0,(ll)s.size()-1){
            if(i!=j){
                t += s[j];
            }
        }
        valid = true;
        ll cur=0;
        exp(t, cur, 0);
        if(cur != (ll)t.size())valid=false;
        if(!valid)continue;
        v.pb(dfs(t, now+1, n));
    }
    string tt = "*+-&^|0123456789";
    rep(i,0,(ll)s.size()){
        rep(j,0,(ll)tt.size()-1){
            //s[i]の前にtt[j]を挿入
            string t;
            rep(k,0,i-1){
                t += s[k];
            }
            t += tt[j];
            rep(k,i,(ll)s.size()-1){
                t += s[k];
            }
            valid = true;
            ll cur=0;
            exp(t, cur, 0);
            if(cur != (ll)t.size())valid=false;
            if(!valid)continue;
            v.pb(dfs(t, now+1, n));
        }
    }
    
    if(now%2 == 0){
        //最大値を返す
        ll maxi = -inf;
        for(ll x : v){
            maxi = max(maxi, x);
        }
        return maxi;
    }else{
        //最小値を返す
        ll mini = inf;
        for(ll x : v){
            mini = min(mini, x);
        }
        return mini;
    }
}

signed main(){fastio
    while(true){
        ll n;cin>>n;
        string s;cin>>s;
        if(s=="#")break;
        if(n%2==0){
            n = 2;
        }else{
            n = 1;
        }
        ll ans = dfs(s, 0, n);
        cout<<ans<<endl;
    }
    return 0;
}
accuracy: 1
time_ms: 280
memory_kb: 3384
final_rank: 13

code_snippet: //#pragma GCC optimize("O3")
//#pragma GCC optimize("unroll-loops")
#include<iostream>
#include<string>
#include<cstdio>
#include<vector>
#include<cmath>
#include<algorithm>
#include<functional>
#include<iomanip>
#include<queue>
#include<ciso646>
#include<random>
#include<map>
#include<set>
#include<bitset>
#include<stack>
#include<unordered_map>
#include<unordered_set>
#include<utility>
#include<cassert>
#include<complex>
#include<numeric>
#include<array>
using namespace std;

//#define int long long
typedef long long ll;

typedef unsigned long long ul;
typedef unsigned int ui;
const ll mod = 998244353;
const ll INF = mod * mod;
typedef pair<int, int>P;

#define rep(i,n) for(int i=0;i<n;i++)
#define per(i,n) for(int i=n-1;i>=0;i--)
#define Rep(i,sta,n) for(int i=sta;i<n;i++)
#define rep1(i,n) for(int i=1;i<=n;i++)
#define per1(i,n) for(int i=n;i>=1;i--)
#define Rep1(i,sta,n) for(int i=sta;i<=n;i++)
#define all(v) (v).begin(),(v).end()
typedef pair<ll, ll> LP;
typedef long double ld;
typedef pair<ld, ld> LDP;
const ld eps = 1e-8;
const ld pi = acosl(-1.0);

ll mod_pow(ll x, ll n, ll m = mod) {
	if (n < 0) {
		ll res = mod_pow(x, -n, m);
		return mod_pow(res, m - 2, m);
	}
	if (abs(x) >= m)x %= m;
	if (x < 0)x += m;
	ll res = 1;
	while (n) {
		if (n & 1)res = res * x % m;
		x = x * x % m; n >>= 1;
	}
	return res;
}
struct modint {
	ll n;
	modint() :n(0) { ; }
	modint(ll m) :n(m) {
		if (n >= mod)n %= mod;
		else if (n < 0)n = (n % mod + mod) % mod;
	}
	operator int() { return n; }
};
bool operator==(modint a, modint b) { return a.n == b.n; }
modint operator+=(modint& a, modint b) { a.n += b.n; if (a.n >= mod)a.n -= mod; return a; }
modint operator-=(modint& a, modint b) { a.n -= b.n; if (a.n < 0)a.n += mod; return a; }
modint operator*=(modint& a, modint b) { a.n = ((ll)a.n * b.n) % mod; return a; }
modint operator+(modint a, modint b) { return a += b; }
modint operator-(modint a, modint b) { return a -= b; }
modint operator*(modint a, modint b) { return a *= b; }
modint operator^(modint a, ll n) {
	if (n == 0)return modint(1);
	modint res = (a * a) ^ (n / 2);
	if (n % 2)res = res * a;
	return res;
}

ll inv(ll a, ll p) {
	return (a == 1 ? 1 : (1 - p * inv(p % a, a)) / a + p);
}
modint operator/(modint a, modint b) { return a * modint(inv(b, mod)); }
modint operator/=(modint& a, modint b) { a = a / b; return a; }
const int max_n = 1 << 2;
modint fact[max_n], factinv[max_n];
void init_f() {
	fact[0] = modint(1);
	for (int i = 0; i < max_n - 1; i++) {
		fact[i + 1] = fact[i] * modint(i + 1);
	}
	factinv[max_n - 1] = modint(1) / fact[max_n - 1];
	for (int i = max_n - 2; i >= 0; i--) {
		factinv[i] = factinv[i + 1] * modint(i + 1);
	}
}
modint comb(int a, int b) {
	if (a < 0 || b < 0 || a < b)return 0;
	return fact[a] * factinv[b] * factinv[a - b];
}
modint combP(int a, int b) {
	if (a < 0 || b < 0 || a < b)return 0;
	return fact[a] * factinv[a - b];
}



int dx[4] = { 1,0,-1,0 };
int dy[4] = { 0,1,0,-1 };

ll gcd(ll x, ll y) {
	x = abs(x), y = abs(y);
	if (x < y)swap(x, y);
	while (y) {
		ll r = x % y; x = y; y = r;
	}
	return x;
}
ll lcd(ll x, ll y) {
	ll g = gcd(x, y);
	return (x / g) * y;
}
bool validterm1(string& s, int& i);
bool validterm2(string& s, int& i);
bool validterm3(string& s, int& i);
bool validterm4(string& s, int& i);
bool validterm5(string& s, int& i);
bool validfactor(string& s, int& i);
bool validnumber(string& s, int& i);

bool validterm1(string& s, int& i) {
	bool res = validterm2(s, i);
	while (i < s.size() && s[i] == '|') {
		i++;
		res &= validterm2(s, i);
	}
	return res;
}
bool validterm2(string& s, int& i) {
	bool res = validterm3(s, i);
	while (i < s.size() && s[i] == '^') {
		i++;
		res &= validterm3(s, i);
	}
	return res;
}
bool validterm3(string& s, int& i) {
	bool res = validterm4(s, i);
	while (i < s.size() && s[i] == '&') {
		i++;
		res &= validterm4(s, i);
	}
	return res;
}
bool validterm4(string& s, int& i) {
	bool res = validterm5(s, i);
	while (i < s.size() && s[i] == '+'||s[i]=='-') {
		i++;
		res &= validterm5(s, i);
	}
	return res;
}
bool validterm5(string& s, int& i) {
	bool res = validfactor(s, i);
	while (i < s.size() && s[i] == '*') {
		i++;
		res &= validfactor(s, i);
	}
	return res;
}
bool validfactor(string& s, int& i) {
	if (i == s.size())return false;
	if (s[i] == '(') {
		i++;
		bool res = validterm1(s, i);
		if (i == s.size())return false;
		if (s[i] != ')')return false;
		i++;
		return res;
	}
	else {
		return validnumber(s, i);
	}
}
bool validnumber(string& s, int& i) {
	if (i == s.size())return false;
	if (s[i] < '1' || '9' < s[i])return false;
	int le = i;
	while ('0' <= s[i] && s[i] <= '9')i++;
	return true;
}
ll term1(string& s, int& i);
ll term2(string& s, int& i);
ll term3(string& s, int& i);
ll term4(string& s, int& i);
ll term5(string& s, int& i);
ll factor(string& s, int& i);
ll number(string& s, int& i);

ll term1(string& s, int& i) {
	ll res = term2(s, i);
	while (i < s.size() && s[i] == '|') {
		i++;
		res |= term2(s, i);
	}
	return res;
}
ll term2(string& s, int& i) {
	ll res = term3(s, i);
	while (i < s.size() && s[i] == '^') {
		i++;
		res ^= term3(s, i);
	}
	return res;
}
ll term3(string& s, int& i) {
	ll res = term4(s, i);
	while (i < s.size() && s[i] == '&') {
		i++;
		res &= term4(s, i);
	}
	return res;
}
ll term4(string& s, int& i) {
	ll res = term5(s, i);
	while (i < s.size() && s[i] == '+'||s[i]=='-') {
		char mem = s[i];
		i++;
		ll nex = term5(s, i);
		if (mem == '+')res += nex;
		else res -= nex;
	}
	return res;
}
ll term5(string& s, int& i) {
	ll res = factor(s, i);
	while (i < s.size() && s[i] == '*') {
		i++;
		res *= factor(s, i);
	}
	return res;
}
ll factor(string& s, int& i) {
	assert(i < s.size());
	//if (i == s.size())return false;
	if (s[i] == '(') {
		i++;
		ll res = term1(s, i);
		assert(i < s.size() && s[i] == ')');
		i++;
		return res;
	}
	else {
		return number(s, i);
	}
}
ll number(string& s, int& i) {
	assert(i < s.size() && '1' <= s[i] && s[i] <= '9');
	int le = i;
	while ('0'<=s[i]&&s[i]<='9')i++;
	return stoll(s.substr(le, i-le));
}

map<string,bool> validmemo;
map<string, ll> valmemo;
bool valid(string s) {
	if (validmemo.find(s) != validmemo.end())return validmemo[s];
	int i = 0;
	bool res = validterm1(s, i);
	if (i != s.size())res = false;
	//cout << s << " " << res << "\n";
	return validmemo[s]=res;
}
ll val(string s) {
	if (valmemo.find(s) != valmemo.end())return valmemo[s];
	int i = 0;
	ll res = term1(s, i);
	assert(i == s.size());
	return valmemo[s] = res;
}

string insertstr = "0123456789*+-&^|()";
map<pair<string, P>,ll> calcmemo;
ll calc(string s, int id, int r) {
	pair<string, P> p = { s,{id,r} };
	if (calcmemo.find(p) != calcmemo.end())return calcmemo[p];
	if (r == 0)return calcmemo[p]=val(s);
	ll res = 0;
	bool upd = false;
	auto needupd = [&](ll a, ll b) {
		if (!upd) {
			upd = true; return true;
		}
		if (id == 0) {
			return a < b;
		}
		else {
			return a > b;
		}
	};
	//erase
	rep(i, s.size()) {
		if (s[i] == '(' || s[i] == ')')continue;
		string ns = s;
		ns.erase(ns.begin() + i);
		if (valid(ns)) {
			ll v = calc(ns,id^1,r-1);
			if (needupd(res, v))res = v;
		}
	}
	//insert
	rep(i, s.size()+1)rep(j,insertstr.size()) {
		if (j >= 16)continue;
		string ns = s;
		ns.insert(ns.begin() + i, insertstr[j]);
		if (valid(ns)) {
			ll v = calc(ns, id ^ 1, r - 1);
			if (needupd(res, v))res = v;
		}
	}
	assert(upd);
	return calcmemo[p] = res;
}

int n; string s;
void solve() {

	//cout << val(s) << "\n";
        while(n>2)n-=2;
	ll ans = calc(s, 0, n);
	cout << ans << "\n";
}



signed main() {
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout << fixed << setprecision(10);
	//init_f();
	//init();
	//int t; cin >> t; rep(i, t)
	while (cin >> n>>s,n)
		solve();
	return 0;
}
accuracy: 1
time_ms: 390
memory_kb: 58752
final_rank: 19

code_snippet: #include <bits/stdc++.h>
using namespace std;

#define rep(i, x) for(int i = 0; i < (x); i++)

int n;
const int inf = 1 << 30;
string input_string;
const string nums = "0123456789";
const string ops = "*!&^|";
const string insert_ops = "*+-&^|";

struct parse_error {};

struct parser {
	using State = string::const_iterator;

public:
	int solve(string s) {
		State begin = s.begin();
		return expr(begin, 4);
	}

private:
	int f(int x, int y, char op) {
		if(op == '*') return x * y;
		if(op == '+') return x + y;
		if(op == '-') return x - y;
		if(op == '&') return x & y;
		if(op == '^') return x ^ y;
		if(op == '|') return x | y;
		throw parse_error();
	}

	bool same(char x, char y) {
		if(x == '+' or x == '-') return y == '!';
		return x == y;
	}

	int expr(State &begin, int type) {
		if(type != -1) {
			int ret = expr(begin, type - 1);
			while(same(*begin, ops[type])) {
				auto op = *begin;
				begin++;
				ret = f(ret, expr(begin, type - 1), op);
			}
			return ret;
		} else {
			if(*begin == '(') {
				begin++;
				int ret = expr(begin, 4);
				begin++;
				return ret;
			} else
				return number(begin);
		}
	}

	int number(State &begin) {
		assert(isdigit(*begin));
		int ret = 0;
		while(isdigit(*begin)) {
			ret *= 10;
			ret += *begin - '0';
			begin++;
		}
		return ret;
	}
} ps;

set<string> gen(string s) {
	set<string> ret;
	const int m = s.size();
	//insert
	rep(i, m + 1) {
		bool lef = i - 1 >= 0 and isdigit(s[i - 1]);
		bool rig = i < m and isdigit(s[i]);
		for(auto num : nums) {
			if(lef or (rig and num != '0')) {
				auto nx = s;
				nx.insert(nx.begin() + i, num);
				ret.insert(nx);
			}
		}
		for(auto op : insert_ops) {
			if(lef and rig and s[i] != '0') {
				auto nx = s;
				nx.insert(nx.begin() + i, op);
				ret.insert(nx);
			}
		}
	}
	//delete
	rep(i, m) {
		bool lef = i - 1 >= 0 and isdigit(s[i - 1]);
		bool rig = i + 1 < m and isdigit(s[i + 1]);
		if(isdigit(s[i])) {
			if(lef or (rig and s[i + 1] != '0')) {
				auto nx = s;
				nx.erase(nx.begin() + i);
				ret.insert(nx);
			}
		} else {
			if(lef and rig) {
				auto nx = s;
				nx.erase(nx.begin() + i);
				ret.insert(nx);
			}
		}
	}
	return ret;
}

int min_max(string s, bool fi = true) {
	if(fi) {
		auto st = gen(s);
		int ret = -inf;
		for(auto &t : st) {
			ret = max(ret, min_max(t, 0));
		}
		return ret;
	} else {
		if(n & 1) {
			return ps.solve(s);
		} else {
			auto st = gen(s);
			int ret = inf;
			for(auto &t : st) {
				ret = min(ret, ps.solve(t));
			}
			return ret;
		}
	}
}

int main() {
	while(true) {
		cin >> n >> input_string;
		if(!n) break;
		cout << min_max(input_string) << endl;
	}
	return 0;
}
accuracy: 1
time_ms: 50
memory_kb: 3412
final_rank: 6

code_snippet: #include <bits/stdc++.h>

using namespace std;

using ll = long long;

using State = string::const_iterator;

class ParseError {};

class ParseError2 {};

vector<int> ps = {2, 3, 3, 4, 5, 6};
const string ops = "*+-&^|";

int f(int a, int b, char t) {
    auto pos = ops.find(t);
    switch (pos) {
        case 0:
            return a * b;
            break;
        case 1:
            return a + b;
            break;
        case 2:
            return a - b;
            break;
        case 3:
            return a & b;
            break;
        case 4:
            return a ^ b;
            break;
        case 5:
            return a | b;
            break;
        default:
            throw ParseError2();
            break;
    }
}

struct solver {
    string S;
    State begin;

    solver(string S_in) { S = S_in; };

    int solve() {
        begin = S.begin();
        return expr(7);
    }

    int expr(int pre) {
        // cerr << pre << (begin - S.begin()) << endl;
        if (pre == 0) {
            int ret;
            if (isdigit(*begin)) {
                ret = 0;
                while (begin != S.end() && isdigit(*begin)) {
                    ret *= 10;
                    ret += *begin - '0';
                    begin++;
                }
                // cout << "ret:" << ret << endl;
            } else if (*begin == '(') {
                begin++;
                ret = expr(7);
                begin++;
            } else if (*begin == '~') {
                begin++;
                ret = !expr(0);
            } else {
                // cerr << (begin - S.begin()) << endl;
                throw ParseError();
            }
            return ret;
        } else {
            int nxt = (pre + 7) % 8;
            auto ret = expr(nxt);
            while (begin != S.end()) {
                char op = *begin;
                auto idx = ops.find(op);
                if (idx == ops.npos || ps[idx] != pre) {
                    break;
                } else {
                    begin++;
                    ret = f(ret, expr(nxt), op);
                }
            }
            return ret;
        }
    }
};

const string nums = "0123456789";

set<string> edit(string S_from) {
    set<string> new_S_set;

    for (int i = 0; i < S_from.size() + 1; i++) {
        for (auto &&d : nums) {
            if (d == '0' && (i == 0 || (!isdigit(S_from[i - 1])))) {
                continue;
            }
            bool ok = 0;
            if (i - 1 >= 0 and isdigit(S_from[i - 1])) ok = 1;
            if (i < S_from.size() and isdigit(S_from[i])) ok = 1;
            if (ok) {
                string S_to = S_from;
                S_to.insert(S_to.begin() + i, d);
                new_S_set.insert(S_to);
            }
        }
        for (auto &&op : ops) {
            if (i < S_from.size() && isdigit(S_from[i]) &&
                i + 1 < S_from.size() && isdigit(S_from[i + 1]) &&
                (S_from[i + 1] != '0')) {
                string S_to = S_from;
                S_to.insert(S_to.begin() + i + 1, op);
                new_S_set.insert(S_to);
            }
        }
    }
    for (int i = 0; i < S_from.size(); i++) {
        if (isdigit(S_from[i])) {
            if ((i == 0 or !isdigit(S_from[i - 1])) && S_from[i + 1] == '0') {
                continue;
            }
            if ((i - 1 >= 0 && isdigit(S_from[i - 1])) ||
                (i + 1 < S_from.size() && isdigit(S_from[i + 1]))) {
                string S_to = S_from;
                S_to.erase(S_to.begin() + i);
                new_S_set.insert(S_to);
            }
        } else if (S_from[i] != '(' && S_from[i] != ')') {
            bool ok = 1;
            if (i - 1 >= 0 and S_from[i - 1] == ')') ok = 0;
            if (i + 1 < S_from.size() and S_from[i + 1] == '(') ok = 0;
            if (ok) {
                string S_to = S_from;
                S_to.erase(S_to.begin() + i);
                new_S_set.insert(S_to);
            }
        }
    }

    return new_S_set;
}

const int inf = 1000000000;

int minmax(string S, int N, bool fi = true) {
    auto es = edit(S);
    if (N % 2) {
        int ret = -inf;
        for (auto &&u : es) {
            solver sv(u);
            // cout << u << ' ' << sv.solve() << endl;
            ret = max(ret, sv.solve());
        }
        return ret;
    } else {
        if (fi) {
            int ret = -inf;
            for (auto &&u : es) {
                // cerr << u << ' ' << minmax(u, N, 0) << endl;
                ret = max(ret, minmax(u, N, 0));
            }
            return ret;
        } else {
            int ret = inf;
            for (auto &&u : es) {
                solver sv(u);
                // cout << u << ' ' << sv.solve() << endl;
                ret = min(ret, sv.solve());
            }
            return ret;
        }
    }
}

int main() {
    int N;
    string S_in;
    while (true) {
        cin >> N;
        if (N == 0) break;
        cin >> S_in;
        cout << minmax(S_in, N) << endl;
    }

    return 0;
}
accuracy: 1
time_ms: 60
memory_kb: 3448
final_rank: 9

code_snippet: #include <bits/stdc++.h>
using namespace std;
using State = string::const_iterator;

int exp_or(State& begin);
int exp_xor(State& begin);
int exp_and(State& begin);
int exp_pm(State& begin);
int exp_mul(State& begin);
int factor(State& begin);
int number(State& begin);
bool fail = false;


int number(State& begin) {
    int ret = 0;
    if (!isdigit(*begin) || *begin == '0') {
        fail = true;
        begin++;
    } else {
        while (isdigit(*begin)) {
            ret *= 10;
            ret += *begin - '0';
            begin++;
        }
    }
    return ret;
}
int factor(State& begin) {
    int ret;
    if (*begin == '(') {
        begin++;
        ret = exp_or(begin);
        if (*begin != ')')
            fail = true;
        begin++;
    } else
        ret = number(begin);
    return ret;
}
int exp_mul(State& begin) {
    int ret = factor(begin);
    while (*begin == '*') {
        begin++;
        ret *= factor(begin);
    }
    return ret;
}
int exp_pm(State& begin) {
    int ret = exp_mul(begin);
    while (*begin == '+' || *begin == '-') {
        bool plus = *begin == '+';
        begin++;
        ret += exp_mul(begin) * (plus ? 1 : -1);
    }
    return ret;
}
int exp_and(State& begin) {
    int ret = exp_pm(begin);
    while (*begin == '&') {
        begin++;
        ret &= exp_pm(begin);
    }
    return ret;
}
int exp_xor(State& begin) {
    int ret = exp_and(begin);
    while (*begin == '^') {
        begin++;
        ret ^= exp_and(begin);
    }
    return ret;
}
int exp_or(State& begin) {
    int ret = exp_xor(begin);
    while (*begin == '|') {
        begin++;
        ret |= exp_xor(begin);
    }
    return ret;
}
int parse(string& S) {
    fail = false;
    State it = S.begin();
    int ret = exp_or(it);
    if (it != S.end())
        fail = true;
    return ret;
}


int N;
string S;

int main() {
    const string rep = "*+-&^|0123456789";
    //const int len = rep.size();
    while (cin >> N >> S, N) {
        if (N % 2)
            N %= 2;
        else
            N = min(N, 2);

        auto calc_nxt = [&](string S) {
            vector<pair<string, int>> nxt;
            auto calc = [&](string S) {
                int res = parse(S);
                if (!fail)
                    nxt.push_back({S, res});
            };
            for (int i = 0; i < S.size(); i++) {
                string T = S;
                if (T[i] != '(' && T[i] != ')') {
                    T.erase(i, 1);
                    calc(T);
                }
            }
            for (int i = 0; i < S.size() + 1; i++) {
                string T = S;
                T.insert(i, ".");
                for (auto c : rep) {
                    T[i] = c;
                    calc(T);
                }
            }
            return nxt;
        };

        int ans;
        if (N == 0) {
            ans = parse(S);
        } else if (N == 1) {
            auto V = calc_nxt(S);
            ans = V[0].second;
            for (auto& [S, val] : V) {
                ans = max(ans, val);
            }
        } else if (N == 2) {
            auto V = calc_nxt(S);
            vector<int> memo;
            for (auto& [S, val] : V) {
                auto W = calc_nxt(S);
                int tmp = W[0].second;
                for (auto& p : W)
                    tmp = min(tmp, p.second);
                memo.emplace_back(tmp);
            }
            ans = *max_element(memo.begin(), memo.end());
        }

        cout << ans << endl;
    }
}
accuracy: 1
time_ms: 20
memory_kb: 3396
final_rank: 2

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

constexpr lint INF = 1LL << 60;

string allops = "|^&+-*";
vector<string> ops({"|", "^", "&", "+-", "*"});

string S;

bool vexpr(lint&);

bool vterm(lint& i) {
	bool ret = true;
	if (S[i] == '(') {
		++i;
		ret = ret && vexpr(i);
		ret = ret && (S[i] == ')');
		++i;
	} else {
		ret = ret && (S[i] != '0');
		lint len = 0;
		while (i + len < S.length() && isdigit(S[i + len])) {
			++len;
		}
		ret = ret && (len > 0);
		i += len;
	}
	return ret;
}

bool vexpr(lint& i) {
	bool ret = vterm(i);

	while (i < S.length() &&
		find(allops.begin(), allops.end(), S[i]) != allops.end()) {
		++i;
		ret = ret && vexpr(i);
	}
	return ret;
}


lint expr(lint&, lint);

lint term(lint& i) {
	// cerr << "term(" << i << ")" << endl;
	lint ret = 0;
	if (S[i] == '(') {
		++i;
		ret = expr(i, 0);
		assert(S[i] == ')');
		++i;
	} else {
		assert(S[i] != '0');
		lint len = 0;
		while (i + len < S.length() && isdigit(S[i + len])) {
			++len;
		}
		assert(len > 0);
		ret = stoll(S.substr(i, len));
		i += len;
	}
	return ret;
}

lint expr(lint& i, lint d) {
	// cerr << "expr(" << i << ", " << d << ")" << endl;
	if (d == 5) return term(i);

	lint ret = expr(i, d + 1);

	while (i < S.length() &&
		find(ops[d].begin(), ops[d].end(), S[i]) != ops[d].end()) {
		char op = S[i];
		++i;
		lint ret2 = expr(i, d + 1);
		// cerr << ret << op << ret2 << endl;
		switch (op) {
			case '*':
				ret *= ret2;
				break;
			case '+':
				ret += ret2;
				break;
			case '-':
				ret -= ret2;
				break;
			case '&':
				ret &= ret2;
				break;
			case '^':
				ret ^= ret2;
				break;
			case '|':
				ret |= ret2;
				break;
			default:
				break;
				// cerr << "op : " << op << endl;
				terminate();
		}
	}
	return ret;
}


lint N;
string ins = "0123456789*+-&^|";

lint calc(lint t, string T) {
	// cerr << t << ":" << T << endl;
	if (t == N) {
		S = T;
		lint i = 0;
		return expr(i, 0);
	}

	lint ret = (t % 2 == 0 ? -INF : INF);
	for(lint i = 0; i <= T.length(); ++i) {
		for(char c : ins) {
			string U = T;
			U.insert(U.begin() + i, c);

			S = U;
			lint j = 0;
			if (vexpr(j) && j == U.length()) {
				if (t % 2 == 0) {
					ret = max(ret, calc(t + 1, U));
				} else {
					ret = min(ret, calc(t + 1, U));
				}
			}
		} 
	}

	for(lint i = 0; i < T.length(); ++i) {
		string U = T;
		U.erase(U.begin() + i);

		S = U;
		lint j = 0;
		if (vexpr(j) && j == U.length()) {
			if (t % 2 == 0) {
				ret = max(ret, calc(t + 1, U));
			} else {
				ret = min(ret, calc(t + 1, U));
			}
		}
	}

	return ret;
}

bool solve() {
	string T;
	cin >> N >> T;
	if (N == 0) return false;
	N %= 2;
	if (N == 0) N = 2;

	cout << calc(0, T) << endl;
	return true;
}

int main() {
	while (solve());
	return 0;
}
accuracy: 1
time_ms: 170
memory_kb: 3084
final_rank: 10

code_snippet: #include <bits/stdc++.h>
using namespace std;
#define inf (int)(1e9)

int is_num(char c){
  if('0' <= c && c <= '9'){
    return 1;
  }
  else{
    return 0;
  }
}

int eval(string s, int l, int r, int d){
  if(l == 1 && r == s.size() - 1){
//    cout << "-" << s << endl;
  }
  if(d == 5){
    if(s[l] == '(' && s[r-1] == ')') return eval(s, l+1, r-1, 0);
    else{
      int ret = 0;
      for(int i = l;i < r;i++){
        ret *= 10;
        ret += s[i]-'0';
      }
      return ret;
    }
  }
  int cnt = 0;
  for(int i = r-1;i >= l;i--){
    if(s[i] == ')') cnt++;
    else if(s[i] == '(') cnt--;
    if(cnt != 0) continue;
    if(s[i] == '*' && d == 4){
      return eval(s,l,i,d)*eval(s,i+1,r,d+1);
    }else if(s[i] == '+' && d == 3){
      return eval(s,l,i,d)+eval(s,i+1,r,d+1);
    }else if(s[i] == '-' && d == 3){
      return eval(s,l,i,d)-eval(s,i+1,r,d+1);
    }else if(s[i] == '&' && d == 2){
      return eval(s,l,i,d)&eval(s,i+1,r,d+1);
    }else if(s[i] == '^' && d == 1){
      return eval(s,l,i,d)^eval(s,i+1,r,d+1);
    }else if(s[i] == '|' && d == 0){
      return eval(s,l,i,d)|eval(s,i+1,r,d+1);
    }
  }
  int ans = eval(s,l,r,d+1);
//  printf("%d\n", ans);
  return ans;
}

int solve(string s){
  int i, ans = -inf;
  string t;
  for(i = 0; i < s.size() - 1; i++){
    if(is_num(s[i]) == 1 || is_num(s[i + 1]) == 1){
      for(char c = '1'; c <= '9'; c++){
        t = s;
        t.insert(i + 1, 1, c);
        ans = max(ans, eval(t, 1, t.size()-1, 0));
      }
      if(is_num(s[i]) == 1){
        t = s;
        t.insert(i + 1, 1, '0');
        ans = max(ans, eval(t, 1, t.size()-1, 0));
      }
    }
    char ops[] = "*+-&^|";
    if(is_num(s[i]) == 1 && is_num(s[i + 1]) == 1 && s[i + 1] > '0'){
      for(int j = 0; j < 6; j++){
        t = s;
        t.insert(i + 1, 1, ops[j]);
        ans = max(ans, eval(t, 1, t.size()-1, 0));
      }
    }
  }
  for(i = 1; i < s.size() - 1; i++){
    if(is_num(s[i - 1]) == 1 && is_num(s[i + 1]) == 1){
      t = s;
      t.erase(i, 1);
      ans = max(ans, eval(t, 1, t.size()-1, 0));
    }
    if(is_num(s[i]) == 1){
      if(is_num(s[i - 1]) == 1){
        t = s;
        t.erase(i, 1);
        ans = max(ans, eval(t, 1, t.size()-1, 0));
      }
      else if(is_num(s[i + 1]) == 1 && s[i + 1] > '0'){
        t = s;
        t.erase(i, 1);
        ans = max(ans, eval(t, 1, t.size()-1, 0));
      }
    }
  }
  return ans;
}

int solve2(string s){
//  cout << s << endl;
  int i, ans = inf;
  string t;
  for(i = 0; i < s.size() - 1; i++){
    if(is_num(s[i]) == 1 || is_num(s[i + 1]) == 1){
      for(char c = '1'; c <= '9'; c++){
        t = s;
        t.insert(i + 1, 1, c);
        ans = min(ans, eval(t, 1, t.size()-1, 0));
      }
      if(is_num(s[i]) == 1){
        t = s;
        t.insert(i + 1, 1, '0');
        ans = min(ans, eval(t, 1, t.size()-1, 0));
      }
    }
    char ops[] = "*+-&^|";
    if(is_num(s[i]) == 1 && is_num(s[i + 1]) == 1 && s[i + 1] > '0'){
//      printf("test2\n");
      for(int j = 0; j < 6; j++){
        t = s;
        t.insert(i + 1, 1, ops[j]);
        ans = min(ans, eval(t, 1, t.size() - 1, 0));
      }
    }
  }
//  printf("ans = %d\n", ans);
  for(i = 1; i < s.size() - 1; i++){
    if(is_num(s[i - 1]) == 1 && is_num(s[i + 1]) == 1){
      t = s;
      t.erase(i, 1);
      ans = min(ans, eval(t, 1, t.size() - 1, 0));
    }
    if(is_num(s[i]) == 1){
      if(is_num(s[i - 1]) == 1){
        t = s;
//        printf("teeeest\n");
//        cout << t << endl;
        t.erase(i, 1);
//        cout << t << endl;
        ans = min(ans, eval(t, 1, t.size()-1, 0));
      }
      else if(is_num(s[i + 1]) == 1 && s[i + 1] > '0'){
//        printf("test\n");
        t = s;
        t.erase(i, 1);
        ans = min(ans, eval(t, 1, t.size()-1, 0));
      }
    }
  }
//  printf("ans = %d\n", ans);
  return ans;
}

int solve1(string s){
  int i, ans = -inf;
  string t;
  for(i = 0; i < s.size() - 1; i++){
    if(is_num(s[i]) == 1 || is_num(s[i + 1]) == 1){
      for(char c = '1'; c <= '9'; c++){
        t = s;
        t.insert(i + 1, 1, c);
        ans = max(ans, solve2(t));
      }
      if(is_num(s[i]) == 1){
        t = s;
        t.insert(i + 1, 1, '0');
        ans = max(ans, solve2(t));
      }
    }
    char ops[] = "*+-&^|";
    if(is_num(s[i]) == 1 && is_num(s[i + 1]) == 1 && s[i + 1] > '0'){
      for(int j = 0; j < 6; j++){
        t = s;
        t.insert(i + 1, 1, ops[j]);
        ans = max(ans, solve2(t));
      }
    }
  }
  for(i = 1; i < s.size() - 1; i++){
    if(is_num(s[i - 1]) == 1 && is_num(s[i + 1]) == 1){
      t = s;
      t.erase(i, 1);
      ans = max(ans, solve2(t));
    }
    if(is_num(s[i]) == 1){
      if(is_num(s[i - 1]) == 1){
        t = s;
        t.erase(i, 1);
        ans = max(ans, solve2(t));
      }
      else if(is_num(s[i + 1]) == 1 && s[i + 1] > '0'){
        t = s;
        t.erase(i, 1);
        ans = max(ans, solve2(t));
      }
    }
  }
  return ans;
}

int main(){
  while(1){
    int N;
    string s;
    scanf("%d", &N);
    cin >> s;
    if(N == 0){
      return 0;
    }
    s.push_back('#');
    s.insert(0, 1, '#');
    if(N % 2 == 1){
      printf("%d\n", solve(s));
    }
    else{
      printf("%d\n", solve1(s));
    }
  }
}
accuracy: 1
time_ms: 260
memory_kb: 3220
final_rank: 12

code_snippet: #include <cstdio>
#include <cstdint>
#include <cassert>
#include <cctype>
#include <map>
#include <vector>
#include <string>
#include <algorithm>
#include <utility>

#define fprintf(...) void(0)

using namespace std::string_literals;

std::vector<std::string> ops={"|", "^", "&", "+-", "*"};

intmax_t parse(const std::string& s, size_t &i, size_t preced) {
  if (i == s.length()) throw 10;
  if (preced == ops.size()) {
    if (s[i] == '(') {
      intmax_t res=parse(s, ++i, 0);
      if (s[i] != ')') throw 0;
      ++i;
      return res;
    }
    if (s[i] == '0') throw 1;
    if (isdigit(s[i])) {
      intmax_t res=s[i]-'0';
      while (++i < s.length() && isdigit(s[i]))
        res = res*10+s[i]-'0';
      return res;
    }
    // fprintf(stderr, "%s[%zu]\n", s.c_str(), i);
    throw 2;
  }

  intmax_t res=parse(s, i, preced+1);
  while (i < s.length()) {
    intmax_t op=s[i];
    if (!std::count(ops[preced].begin(), ops[preced].end(), op)) break;
    intmax_t tmp=parse(s, ++i, preced+1);
    if (op == '*') res *= tmp;
    if (op == '+') res += tmp;
    if (op == '-') res -= tmp;
    if (op == '&') res &= tmp;
    if (op == '^') res ^= tmp;
    if (op == '|') res |= tmp;
    if (op == '(' || op == ')' || isdigit(op)) throw 9;
  }
  return res;
}

void validate(const std::string& s) {
  size_t i=0;
  parse(s, i, 0);
  if (i != s.length()) throw 1;
}

intmax_t optimize(const std::string& s, int n, int k) {
  if (s.empty()) throw -1;

  if (k == n) {
    size_t j=0;

    intmax_t res=parse(s, j, 0);
    if (j != s.length()) throw 3;
    fprintf(stderr, "< %s (%jd)\n", s.c_str(), res);
    return res;
  }

  intmax_t res=(k%2? 1e18:-1e18);
  auto opt=[=](intmax_t x, intmax_t y) {
             return k%2? std::min(x, y):std::max(x, y);
           };

  std::string u=".";
  u += s;
  for (char c='1'; c<='9'; ++c) {
    u[0] = c;
    if (k == 0) fprintf(stderr, "--- %s\n", u.c_str());
    try {
      validate(u);
      res = opt(res, optimize(u, n, k+1));
    } catch (int e) {}
  }

  // (1+2+3)
  //       ^

  for (size_t i=0; i<s.length(); ++i) {
    // insertible?
    u[i] = s[i];

    for (char c: "*+-&^|0123456789"s) {
      u[i+1] = c;
      try {
        if (k == 0) fprintf(stderr, "--- %s\n", u.c_str());
        validate(u);
        res = opt(res, optimize(u, n, k+1));
      } catch (int e) {}
    }
  }

  std::string t=s.substr(1);
  for (size_t i=0; i<s.length(); ++i) {
    // removable?
    try {
      if (k == 0) fprintf(stderr, "--- %s\n", t.c_str());
      validate(t);
      res = opt(res, optimize(t, n, k+1));
    } catch (int e) {}
    if (i < t.length()) t[i] = s[i];
  }

  return res;
}

int testcase_ends() {
  int N;
  char buf[16];
  scanf("%d %s", &N, buf);
  std::string s=buf;

  if (N == 0 && s == "#") return 1;

  N %= 2;
  if (!N) N += 2;
  fprintf(stderr, "> %s\n", s.c_str());

  printf("%jd\n", optimize(s, N, 0));
  return 0;
}

int main() {
  while (!testcase_ends()) {}
}
accuracy: 1
time_ms: 680
memory_kb: 2928
final_rank: 17

code_snippet: #include<bits/stdc++.h>
typedef long long int ll;
typedef unsigned long long int ull;
#define BIG_NUM 2000000000
#define HUGE_NUM 99999999999999999
#define MOD 1000000007
#define EPS 0.000000001
using namespace std;


#define NUM 20
#define SIZE 16

int N;
char add[SIZE] = {'|','^','&','+','-','*','0','1','2','3','4','5','6','7','8','9'};

ll calc_EXP(char line[NUM],int left,int right);
ll calc_OR(char line[NUM],int left,int right);
ll calc_XOR(char line[NUM],int left,int right);
ll calc_AND(char line[NUM],int left,int right);
ll calc_PLUS_MINUS(char line[NUM],int left,int right);
ll calc_MULT(char line[NUM],int left,int right);
ll getNUM(char line[NUM],int left,int right);


//指定された範囲で、深さ0のopを探す関数
queue<int> find_op(char op,char line[NUM],int left,int right){

	queue<int> RET;

	int depth = 0;

	for(int i = left; i <= right; ){
		if(line[i] == '(')depth++;
		else if(line[i] == ')')depth--;

		if(depth != 0){
			i++;
		}else{

			if((line[i] == op) || ((line[i] == '+' || line[i] == '-') && op == '@')){ //@:+または-
				RET.push(i);
				i++;
			}else{ //単項演算子なし
				i++;
			}
		}
	}

	return RET;
}

ll getNUM(char line[NUM],int left,int right){

	if(left > right){
		return HUGE_NUM;
	}

	//left～righgtの間に、非数字があったら誤り
	for(int i = left; i <= right; i++){
		if(line[i] < '0' || line[i] > '9'){
			return HUGE_NUM;
		}
	}

	if(line[left] == '0'){ //正の数でなければ不可
		return HUGE_NUM;
	}

	ll ret = 0;

	for(int i = left; i <= right; i++){
		ret = 10*ret+(line[i]-'0');
	}

	return ret;
}

ll calc_MULT(char line[NUM],int left,int right){

	if(left > right){
		return HUGE_NUM;
	}

	ll tmp;

	if(line[left] == '('){

		if(line[right] != ')'){
			return HUGE_NUM;
		}

		tmp = calc_EXP(line,left+1,right-1);

	}else if(line[left] >= '0' && line[left] <= '9'){ //数字

		tmp = getNUM(line,left,right);

	}else{ //文法誤り
		return HUGE_NUM;
	}

	return tmp;
}

ll calc_PLUS_MINUS(char line[NUM],int left,int right){

	if(left > right){
		return HUGE_NUM;
	}

	queue<int> Q = find_op('*',line,left,right);

	if(Q.empty()){
		return calc_MULT(line,left,right);
	}

	ll tmp = calc_PLUS_MINUS(line,left,Q.front()-1),tmp_right;

	if(tmp == HUGE_NUM)return HUGE_NUM;

	while(!Q.empty()){
		int loc = Q.front();
		Q.pop();

		if(Q.empty()){
			tmp_right = calc_MULT(line,loc+1,right);
		}else{
			tmp_right = calc_MULT(line,loc+1,Q.front()-1);
		}

		if(tmp_right == HUGE_NUM){
			return HUGE_NUM;
		}

		tmp *= tmp_right;
	}
	return tmp;
}

ll calc_AND(char line[NUM],int left,int right){

	if(left > right){
		return HUGE_NUM;
	}

	queue<int> Q = find_op('@',line,left,right);

	if(Q.empty()){
		return calc_PLUS_MINUS(line,left,right);
	}

	ll tmp = calc_AND(line,left,Q.front()-1),tmp_right;

	if(tmp == HUGE_NUM)return HUGE_NUM;

	while(!Q.empty()){
		int loc = Q.front();
		Q.pop();

		if(Q.empty()){
			tmp_right = calc_PLUS_MINUS(line,loc+1,right);
		}else{
			tmp_right = calc_PLUS_MINUS(line,loc+1,Q.front()-1);
		}

		if(tmp_right == HUGE_NUM){
			return HUGE_NUM;
		}

		if(line[loc] == '+'){
			tmp += tmp_right;
		}else{
			tmp -= tmp_right;
		}
	}
	return tmp;
}

ll calc_XOR(char line[NUM],int left,int right){

	if(left > right){
		return HUGE_NUM;
	}

	queue<int> Q = find_op('&',line,left,right);

	if(Q.empty()){
		return calc_AND(line,left,right);
	}

	ll tmp = calc_XOR(line,left,Q.front()-1),tmp_right;

	if(tmp == HUGE_NUM)return HUGE_NUM;

	while(!Q.empty()){
		int loc = Q.front();
		Q.pop();

		if(Q.empty()){
			tmp_right = calc_AND(line,loc+1,right);
		}else{
			tmp_right = calc_AND(line,loc+1,Q.front()-1);
		}

		if(tmp_right == HUGE_NUM){
			return HUGE_NUM;
		}

		tmp &= tmp_right;
	}
	return tmp;
}

ll calc_OR(char line[NUM],int left,int right){

	if(left > right){
		return HUGE_NUM;
	}

	queue<int> Q = find_op('^',line,left,right);

	if(Q.empty()){
		return calc_XOR(line,left,right);
	}

	ll tmp = calc_OR(line,left,Q.front()-1),tmp_right;

	if(tmp == HUGE_NUM)return HUGE_NUM;

	while(!Q.empty()){
		int loc = Q.front();
		Q.pop();

		if(Q.empty()){
			tmp_right = calc_XOR(line,loc+1,right);
		}else{
			tmp_right = calc_XOR(line,loc+1,Q.front()-1);
		}

		if(tmp_right == HUGE_NUM){
			return HUGE_NUM;
		}

		tmp ^= tmp_right;
	}
	return tmp;
}

bool is_op(char ch){
	if(ch == '|' || ch == '^' || ch == '&' || ch == '+' || ch == '-' || ch == '*'){
		return true;
	}else{
		return false;
	}
}


ll calc_EXP(char line[NUM],int left,int right){

	if(right < left){
		return HUGE_NUM;
	}

	//left～rightの区間にある、orを探す
	queue<int> Q = find_op('|',line,left,right);

	//深さ0のorがない
	if(Q.empty()){
		return calc_OR(line,left,right);
	}

	ll tmp = calc_EXP(line,left,Q.front()-1),tmp_right;

	if(tmp == HUGE_NUM)return HUGE_NUM;

	while(!Q.empty()){
		int loc = Q.front();
		Q.pop();

		if(Q.empty()){
			tmp_right = calc_OR(line,loc+1,right);
		}else{
			tmp_right = calc_OR(line,loc+1,Q.front()-1);
		}

		if(tmp_right == HUGE_NUM){
			return HUGE_NUM;
		}

		tmp |= tmp_right;
	}
	return tmp;
}

void add_char(char line[NUM],int length,int loc,char ch){

	if(loc == length){
		line[loc] = ch;
		return;
	}

	queue<char> Q;
	for(int i = loc; i < length; i++){
		Q.push(line[i]);
	}
	line[loc] = ch;

	int index = loc+1;

	while(!Q.empty()){

		line[index++] = Q.front();
		Q.pop();
	}
}

void del_char(char line[NUM],int length,int loc){

	for(int i = loc+1; i < length; i++){
		line[i-1] = line[i];
	}
}

void copy_line(char line[NUM],char base[NUM],int length){

	for(int i = 0; i < length; i++){
		line[i] = base[i];
	}
}

void func(char buf[NUM]){

	int length;
	for(length = 0; buf[length] != '\0'; length++);


	ll tmp,ans;

	char work[NUM];

	if(N%2 == 1){ //結果を最大化する

		ans = -HUGE_NUM;

		//1文字加える
		for(int loc = 0; loc <= length; loc++){
			for(int i = 0; i < SIZE; i++){
				copy_line(work,buf,length);
				add_char(work,length,loc,add[i]);
				tmp = calc_EXP(work,0,length);
				if(tmp == HUGE_NUM)continue;

				ans = max(ans,tmp);
			}
		}

		//1文字削る
		for(int loc = 0; loc <= length-1; loc++){
			copy_line(work,buf,length);
			del_char(work,length,loc);
			tmp = calc_EXP(work,0,length-2);
			if(tmp == HUGE_NUM)continue;

			ans = max(ans,tmp);
		}

	}else{ //先手が2ターン全探索した最良値を選ぶはず

		ans = -HUGE_NUM;
		char gote_work[NUM];
		ll tmp_ans,result;

		//先手が1文字加える
		for(int loc = 0; loc <= length; loc++){
			for(int i = 0; i < SIZE; i++){

				copy_line(work,buf,length);
				add_char(work,length,loc,add[i]);
				tmp = calc_EXP(work,0,length);
				if(tmp == HUGE_NUM)continue;

				tmp_ans = HUGE_NUM;

				//後手が1文字加える
				for(int gote_loc = 0; gote_loc <= length+1; gote_loc++){
					for(int k = 0; k < SIZE; k++){
						copy_line(gote_work,work,length+1);
						add_char(gote_work,length+1,gote_loc,add[k]);
						result = calc_EXP(gote_work,0,length+1);
						if(result == HUGE_NUM)continue;

						tmp_ans = min(tmp_ans,result); //★★後手は結果を最小化しようとする★★
					}
				}

				//後手が1文字削る
				for(int gote_loc = 0; gote_loc <= length; gote_loc++){
					copy_line(gote_work,work,length+1);
					del_char(gote_work,length+1,gote_loc);
					result = calc_EXP(gote_work,0,length-1);
					if(result == HUGE_NUM)continue;

					tmp_ans = min(tmp_ans,result);
				}

				if(tmp_ans != HUGE_NUM){
					ans = max(ans,tmp_ans); //最小値の最大値
				}
			}
		}

		//先手が1文字削る
		for(int loc = 0; loc <= length-1; loc++){
			copy_line(work,buf,length);
			del_char(work,length,loc);
			tmp = calc_EXP(work,0,length-2);
			if(tmp == HUGE_NUM)continue;

			tmp_ans = HUGE_NUM;

			//後手が1文字加える
			for(int gote_loc = 0; gote_loc <= length-1; gote_loc++){
				for(int k = 0; k < SIZE; k++){
					copy_line(gote_work,work,length-1);
					add_char(gote_work,length-1,gote_loc,add[k]);
					result = calc_EXP(gote_work,0,length-1);
					if(result == HUGE_NUM)continue;

					tmp_ans = min(tmp_ans,result); //★★後手は結果を最小化しようとする★★
				}
			}

			//後手が1文字削る
			for(int gote_loc = 0; gote_loc <= length-2; gote_loc++){
				copy_line(gote_work,work,length-1);
				del_char(gote_work,length-1,gote_loc);
				result = calc_EXP(gote_work,0,length-3);
				if(result == HUGE_NUM)continue;

				tmp_ans = min(tmp_ans,result);
			}

			if(tmp_ans != HUGE_NUM){
				ans = max(ans,tmp_ans); //最小値の最大値
			}
		}
	}

	printf("%lld\n",ans);
}

int main(){


	char buf[NUM];

	while(true){
		scanf("%d %s",&N,buf);
		if(N == 0 && buf[0] == '#')break;

		func(buf);
	}

	return 0;
}
accuracy: 1
time_ms: 750
memory_kb: 3232
final_rank: 18