Problem:
Tree Transformation Puzzle
Let's get started with a puzzle!
First, you are given an arithmetic expression, which solely consists of integers, operator symbols
+
and
−
, and parentheses.
(4−1)−(2+3)−(5+6)
is an example of such an expression.
As is well known, the structure of an arithmetic expression is naturally represented as a
tree
.
For instance, the tree in Figure C-1 represents
(4−1)−(2+3)−(5+6)
.
Figure C-1: A tree representation of
(4−1)−(2+3)−(5+6)
In the tree of the figure, each box is a leaf node labeled with an integer, and each circle is a non-leaf node labeled with an operator symbol
+
or
−
.
The value of a leaf node labeled with an integer is that integer.
The value of a node with an operator symbol
+
is the sum of the values of all of its child nodes.
The value of a node with an operator symbol
−
is the value of its leftmost child node subtracted with the values of all the other child nodes.
The value of the root node calculated in this manner is equal to the value of the given expression calculated with
the usual rules of arithmetic, of course.
For any trees representing arithmetic expressions given for this puzzle, the root nodes have three child nodes, and all the other non-leaf nodes have one parent and two child nodes.
Therefore, every non-leaf node is directly connected to exactly three nodes.
Let us think of transformation of the tree structure corresponding to the given arithmetic expression by applying either of the following operations on the entire tree or any of its subtrees arbitrarily many times.
Swapping two child nodes of a non-leaf node.
For the leftmost (or the rightmost) child node of the root, if it is a non-leaf, making it the new root of the tree and the old root node the rightmost (or the leftmost, respectively) child node of the new root.
Unless explicitly stated above, these operations change neither the parent-child relationship between two nodes nor the left-to-right order among child nodes sharing the same parent.
The new tree resulted from such operations represents a possibly different arithmetic expression having a possibly different value.
The goal of this puzzle is to find the maximum possible value of such an expression through the operations described above applied arbitrarily many times.
For example, by swapping the two child nodes of the leftmost non-leaf node in Figure C-1, which has an operator symbol
−
, you will have the tree in Figure C-2.
Figure C-2: The result of swapping the two leftmost leaf nodes
And then by swapping the leftmost and the rightmost child nodes of the root in Figure C-2, you will have the tree in Figure C-3.
The value of the original arithmetic expression
(4−1)−(2+3)−(5+6)
is −13, and those of the expressions represented by the two trees in Figures C-2 and C-3 are −19 and 9, respectively.
Figure C-3: The result of swapping the leftmost and the rightmost nodes of the root
In addition, by making the leftmost child node of the root in Figure C-3 the new root, and the origin
...(truncated)

Submitted solutions:

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

//https://onlinejudge.u-aizu.ac.jp/services/ice/?problemId=1650
//模擬解答を参考

const int INF = 1e9; //非常に大きな値

struct Node {
    char op; // '+', '-', or '@' (葉ノード)
    int val; // if op == '@'
    vector<int> children;
};

const int MAX_NODE = 500005;
const int MAX_DEPTH = 105;

char expr[MAX_NODE]; // expression 入力された式を格納する文字列（例："(+ 1 (- 2 3))"）
Node tree[MAX_NODE]; // 構文木
int dp_max[MAX_NODE], dp_min[MAX_NODE]; // 各ノードにおける部分木の最大値・最小値を表す
int ans_max[MAX_NODE], ans_min[MAX_NODE]; // 各ノードを「根」に持ってきたときの、全体の最大値・最小値
int pre_max[MAX_NODE], pre_min[MAX_NODE]; // 親ノード側の情報を使って、自分を根にしたときに必要な補助データ
vector<int> op_pos_by_depth[MAX_DEPTH]; // 各深さごとに、'+', '-' の演算子が出現する位置
int node_cnt = 0; // ノード数を管理するカウンター

// 葉ノード
int make_leaf(int val) {
    ++node_cnt;
    tree[node_cnt].op = '@';
    tree[node_cnt].val = val;
    return node_cnt;
}

// 构造表达式
int parse_expr(int l, int r, int depth);
// l〜rの部分式を、優先順位が低い演算子（+や-）に基づいて解析する関数
// depth：現在の括弧の深さ（V[depth] を使うために渡す）
// 戻り値：tree[]配列に構築されたノードのインデックス
int parse_factor(int l, int r, int depth);
// 数字や括弧で囲まれた小さい式を処理する関数
// 基本的に「葉ノード」になる数字か、もう一つの `parse_expr` を呼ぶ
// 戻り値：tree[]配列に構築されたノードのインデックス

int parse_expr(int l, int r, int depth) {
    vector<int> ops; //depth +-の位置
    auto& v = op_pos_by_depth[depth];
    int L = lower_bound(v.begin(), v.end(), l) - v.begin();
    int R = upper_bound(v.begin(), v.end(), r) - v.begin() - 1;

    for (int i = L; i <= R; i++) ops.push_back(v[i]);

    if (ops.empty()) return parse_factor(l, r, depth);

    if (depth == 0) {
        tree[0].op = expr[ops[0]];
        tree[0].children.push_back(parse_factor(l, ops[0] - 1, depth));
        tree[0].children.push_back(parse_factor(ops[0] + 1, ops[1] - 1, depth));
        tree[0].children.push_back(parse_factor(ops[1] + 1, r, depth));
        return 0;
    } else {
        ++node_cnt;
        int cur = node_cnt;
        tree[cur].op = expr[ops[0]];
        tree[cur].children.push_back(parse_factor(l, ops[0] - 1, depth));
        tree[cur].children.push_back(parse_factor(ops[0] + 1, r, depth));
        return cur;
    }
}

int parse_factor(int l, int r, int depth) {
    if (isdigit(expr[l])) return make_leaf(expr[l] - '0');
    return parse_expr(l + 1, r - 1, depth + 1);
}


void dfs(int node) {
    if (tree[node].op == '@') {
        dp_min[node] = dp_max[node] = tree[node].val;
        return;
    }

    for (int child : tree[node].children) dfs(child);

    if (tree[node].op == '+') {
        dp_min[node] = dp_max[node] = 0;
        for (int child : tree[node].children) {
            dp_min[node] += dp_min[child];
            dp_max[node] += dp_max[child];
        }
    } else { // '-'
        dp_max[node] = -INF;
        dp_min[node] = INF;

        for (int i = 0; i < tree[node].children.size(); i++) {
            int left = tree[node].children[i];
            int max_val = dp_max[left], min_val = dp_min[left];

            for (int j = 0; j < tree[node].children.size(); j++) {
                if (i == j) continue;
                int right = tree[node].children[j];
                max_val -= dp_min[right];
                min_val -= dp_max[right];
            }

            dp_max[node] = max(dp_max[node], max_val);
            dp_min[node] = min(dp_min[node], min_val);
        }
    }
}


void dfs2(int node, int parent) {
    if (node == 0) {
        ans_max[node] = dp_max[node];
        ans_min[node] = dp_min[node];
    } else {
        if (tree[node].op == '@') return;

        if (tree[parent].op == '+') {
            pre_max[node] = ans_max[parent] - dp_max[node];
            pre_min[node] = ans_min[parent] - dp_min[node];
        } else {
            if (parent == 0) {
                vector<int> rest;
                for (int c : tree[parent].children) if (c != node) rest.push_back(c);

                pre_max[node] = max(
                    dp_max[rest[0]] - dp_min[rest[1]],
                    dp_max[rest[1]] - dp_min[rest[0]]
                );
                pre_min[node] = min(
                    dp_min[rest[0]] - dp_max[rest[1]],
                    dp_min[rest[1]] - dp_max[rest[0]]
                );
            } else {
                int sibling; //兄弟
                for (int c : tree[parent].children) {
                    if (c != node) {
                        sibling = c;
                        break;
                    }
                }

                pre_max[node] = max(
                    dp_max[sibling] - pre_min[parent],
                    pre_max[parent] - dp_min[sibling]
                );
                pre_min[node] = min(
                    dp_min[sibling] - pre_max[parent],
                    pre_min[parent] - dp_max[sibling]
                );
            }
        }

        if (tree[node].op == '+') {
            ans_max[node] = dp_max[node] + pre_max[node];
            ans_min[node] = dp_min[node] + pre_min[node];
        } else {
            int a = tree[node].children[0];
            int b = tree[node].children[1];

            ans_max[node] = max({
                dp_max[a] - (dp_min[b] + pre_min[node]),
                dp_max[b] - (dp_min[a] + pre_min[node]),
                pre_max[node] - (dp_min[a] + dp_min[b])
            });

            ans_min[node] = min({
                dp_min[a] - (dp_max[b] + pre_max[node]),
                dp_min[b] - (dp_max[a] + pre_max[node]),
                pre_min[node] - (dp_max[a] + dp_max[b])
            });
        }
    }

    for (int child : tree[node].children) dfs2(child, node);
}

void solve() {
    //初期化
    for (int i = 0; i < MAX_DEPTH; i++) op_pos_by_depth[i].clear();
    for (int i = 0; i < MAX_NODE; i++) tree[i].children.clear();

    int len = strlen(expr);
    int depth = 0;
    for (int i = 0; i < len; i++) {
        if (expr[i] == '(') depth++;
        else if (expr[i] == ')') depth--;
        else if (expr[i] == '+' || expr[i] == '-') op_pos_by_depth[depth].push_back(i);
    }

    node_cnt = 0;
    parse_expr(0, len - 1, 0);

    for (int i = 0; i <= node_cnt; i++) {
        dp_min[i] = ans_min[i] = INF;
        dp_max[i] = ans_max[i] = -INF;
    }

    dfs(0);
    dfs2(0, -1);

    int res = -INF;
    for (int i = 0; i <= node_cnt; i++) {
        if (tree[i].op != '@') res = max(res, ans_max[i]);
    }

    printf("%d\n", res);
}

int main() {
    while (true) {
        scanf("%s", expr);
        if (strcmp(expr, "-1") == 0) break;
        solve();
    }
    return 0;
}
accuracy: 1
time_ms: 40
memory_kb: 33760
final_rank: 11

code_snippet: #include <bits/stdc++.h>
using namespace std;
const int INF = 1001001001;
#ifdef _DEBUG
#define show(x)          \
	cerr << #x << " : "; \
	showVal(x)
template <typename T>
void showVal(const T &a) {
	cerr << a << endl;
}
template <typename T, typename U>
void showVal(const pair<T, U> &a) {
	cerr << a.first << " " << a.second << endl;
}
template <typename T>
void showVal(const vector<T> &a) {
	for (const T &v : a) cerr << v << " ";
	cerr << endl;
}
template <typename T, typename U>
void showVal(const vector<pair<T, U>> &a) {
	cerr << endl;
	for (const pair<T, U> &v : a) cerr << v.first << " " << v.second << endl;
}
template <typename T, typename U>
void showVal(const map<T, U> &a) {
	cerr << endl;
	for (const auto &v : a) cerr << "[" << v.first << "] " << v.second << endl;
}
template <typename T>
void showVal(const vector<vector<T>> &a) {
	cerr << endl;
	for (const vector<T> &v : a) showVal(v);
}
#else
#define show(x)
#endif
template <typename T>
bool chmin(T &a, const T &b) {
	if (b < a) {
		a = b;
		return true;
	}
	return false;
}
template <typename T>
bool chmax(T &a, const T &b) {
	if (a < b) {
		a = b;
		return true;
	}
	return false;
}
int main() {
	while (1) {
		string s;
		cin >> s;
		if (s == "-1") break;
		int sz = s.size();
		vector<vector<int>> g(sz);
		{
			stack<pair<int, int>> st;
			vector<int> threei;
			map<pair<int, int>, int> lrtom;
			for (int i = 0; i < sz; i++) {
				if (s[i] == '(') {
					st.push({i, -1});
				} else if (s[i] == ')') {
					auto [l, m] = st.top();
					lrtom[{l, i}] = m;
					st.pop();
				} else if (s[i] == '-' || s[i] == '+') {
					if (st.size() == 0) {
						threei.push_back(i);
					} else {
						st.top().second = i;
					}
				}
			}
			assert(threei.size() == 2);
			auto dfs = [&](auto self, int l, int r, int par) {
				if (l == r) {
					g[par].push_back(l);
					g[l].push_back(par);
					return;
				}
				int m = lrtom[{l, r}];
				g[m].push_back(par);
				g[par].push_back(m);
				self(self, l + 1, m - 1, m);
				self(self, m + 1, r - 1, m);
				return;
			};
			int root = threei[0];
			dfs(dfs, 0, threei[0] - 1, root);
			dfs(dfs, threei[0] + 1, threei[1] - 1, root);
			dfs(dfs, threei[1] + 1, sz - 1, root);
		}
		// show(g);

		auto combminmax = [&](const vector<pair<int, int>> &vals, char op) {
			// show(vals);
			// show(op);
			int n = vals.size();
			vector<int> res;
			for (int bit = 0; bit < (1 << n); bit++) {
				int tot = (bit & 1) ? vals[0].first : vals[0].second;
				for (int i = 1; i < n; i++) {
					int tv = ((bit >> i) & 1) ? vals[i].first : vals[i].second;
					if (op == '+')
						tot += tv;
					else
						tot -= tv;
				}
				res.push_back(tot);
			}
			int mins = *min_element(res.begin(), res.end());
			int maxs = *max_element(res.begin(), res.end());
			// show(mins);
			// show(maxs);
			return pair<int, int>{mins, maxs};
		};

		map<pair<int, int>, pair<int, int>> memo;
		auto f = [&](auto self, int i, int j) -> pair<int, int> {
			if (memo.count({i, j})) return memo[{i, j}];
			//  -> i ? -> j
			vector<pair<int, int>> vals;
			for (auto v : g[i]) {
				if (v == j) continue;
				vals.push_back(self(self, v, i));
			}
			pair<int, int> res;
			if (vals.size() == 0) {
				res.first = s[i] - '0';
				res.second = s[i] - '0';
			} else {
				assert(vals.size() == 2);
				show(i);
				show(j);
				auto [mins1, maxs1] = combminmax(vals, s[i]);
				reverse(vals.begin(), vals.end());
				auto [mins2, maxs2] = combminmax(vals, s[i]);
				res.first = min(mins1, mins2);
				res.second = max(maxs1, maxs2);
			}
			memo[{i, j}] = res;
			return res;
		};
		int ans = -INF;
		for (int i = 0; i < sz; i++) {
			if (g[i].size() == 3) {
				show(i);
				vector<int> sg(3);
				for (int j = 0; j < 3; j++) {
					sg[j] = j;
				}
				do {
					vector<pair<int, int>> vals;
					for (int j = 0; j < 3; j++) {
						vals.push_back(f(f, g[i][sg[j]], i));
					}
					chmax(ans, combminmax(vals, s[i]).second);
				} while (next_permutation(sg.begin(), sg.end()));
				show(ans);
			}
		}
		// for (auto [p, q] : memo) {
		// 	show(p);
		// 	show(q);
		// }
		cout << ans << endl;
	}
	return 0;
}
accuracy: 1
time_ms: 370
memory_kb: 38120
final_rank: 20

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

using ll = long long;
#define rep(i, a, b) for (int i = a; i < (b); ++i)
#define sz(x) (int)(x).size()
#define all(x) x.begin(), x.end()
typedef pair<int, int> pii;
typedef vector<int> vi;
template <class T>
inline bool chmin(T &a, T b) {
  return ((a > b) ? (a = b, 1) : (0));
}
template <class T>
inline bool chmax(T &a, T b) {
  return ((a < b) ? (a = b, 1) : (0));
}

int main() {
  while (solve());
  return 0;
}

struct Node{
  vector<Node*>ns;
  char c;
  int idx;
};

bool solve() {
  string s;
  Node root;
  cin>>s;
  if (s=="-1") return 0;
  //構文解析
  vector<char>val;
  stack<Node>st;
  vector<vi>G;
  auto add_edge=[&](Node u,Node v)->void{
    while(sz(G)<=max(u.idx,v.idx))G.push_back({});
    G[u.idx].push_back(v.idx);
    G[v.idx].push_back(u.idx);
  };
  int n=0;
  rep(i,0,sz(s)){
    if(s[i]=='(')continue;
    if(s[i]==')'){
      assert(sz(st)>=3);
      Node n1=st.top();st.pop();
      Node n2=st.top();st.pop();
      Node n3=st.top();st.pop();
      add_edge(n1,n2);
      add_edge(n2,n3);
      st.push(n2);
      continue;
    }
    Node node;
    node.c=s[i];
    node.idx=n++;
    while(sz(val)<=n)val.push_back({});
    val[node.idx]=node.c;
    st.push(node);
  }
  assert(sz(st)==5);
  {
      Node n1=st.top();st.pop();
      Node n2=st.top();st.pop();
      Node n3=st.top();st.pop();
      Node n4=st.top();st.pop();
      Node n5=st.top();st.pop();
      root.c=n2.c;
      root.idx=n++;
      while(sz(val)<=n)val.push_back({});
      val[root.idx]=root.c;
      // cout<<root.c<<endl;
      add_edge(root,n1);
      add_edge(root,n3);
      add_edge(root,n5);
  }
  assert(sz(st)==0);

  
  //全方位木dp 最大と最小をもっておく
  vector<pii>dp(n);//max,min
  pii ini={-1e7,1e7};
  //木dp
  auto dfs1=[&](auto dfs1,int v,int p)->pii{
    pii ret=ini;
    vector<pii> chd_val;
    // cout<<v<<"totunyuu"<<endl;
    for(auto to:G[v]){
      if(to==p)continue;
      chd_val.push_back(dfs1(dfs1,to,v));
    }
    if(val[v]=='+'){
      ret=pii(0,0);
      for(auto [mx,mn]:chd_val)ret.first+=mx,ret.second+=mn;
    }else if(val[v]=='-'){
      //4~8通りしかない
      rep(i,0,sz(chd_val)){
        //iだけmin,他max
        int mnx=chd_val[i].second;
        //iだけmax,他min
        int mxn=chd_val[i].first;
        //iのところだけ+
        rep(j,0,sz(chd_val)){
          if(j==i)continue;
          mnx-=chd_val[j].first;
          mxn-=chd_val[j].second;
        }
        ret.first=max(ret.first,mxn);
        ret.second=min(ret.second,mnx);
      }
    }
    else ret=pii(val[v]-'0',val[v]-'0');
    dp[v]=ret;
    //     cout<<"頂点"<<v<<" "<<val[v]<<endl;
    // cout<<dp[v].first<<" "<<dp[v].second<<endl;
// cout<<v<<" "<<val[v]<<endl;    cout<<dp[v].first<<" "<<dp[v].second<<endl;
    return ret;
  };
  dfs1(dfs1,root.idx,-1);
  // cout<<dp[0].first<<" "<<dp[0].second<<endl;
  // cout<<endl;
  int ans=dp[root.idx].first;

  auto dfs2=[&](auto dfs2,int v,int p,pii p_val)->pii{
    pii ret=ini;
    vector<pii> chd_val;
    for(auto to:G[v]){
      if(to==p)chd_val.push_back(p_val);
      else chd_val.push_back(dp[to]);
    }
    if(val[v]=='+'){
      ret=pii(0,0);
      for(auto [mx,mn]:chd_val)ret.first+=mx,ret.second+=mn;
    }else if(val[v]=='-'){
      //4~8通りしかない
      rep(i,0,sz(chd_val)){
        //iだけmin,他max
        int mnx=chd_val[i].second;
        //iだけmax,他min
        int mxn=chd_val[i].first;
        //iのところだけ+
        rep(j,0,sz(chd_val)){
          if(j==i)continue;
          mnx-=chd_val[j].first;
          mxn-=chd_val[j].second;
        }
        ret.first=max(ret.first,mxn);
        ret.second=min(ret.second,mnx);
      }
    }
    else ret=pii(val[v]-'0',val[v]-'0');
    if(!isdigit(val[v]))ans=max(ans,ret.first);

    if(v==root.idx)assert(dp[v]==ret);
    // dp[v]=ret;//kokonohamotomatta
    if(isdigit(val[v]))return ret;

    rep(rm,0,sz(G[v])){
      // cout<<v<<"突入"<<endl;
      chd_val.clear();
      ret=ini;
      for(auto to:G[v]){
        if(to==p)chd_val.push_back(p_val);
        else chd_val.push_back(dp[to]);
      }
      chd_val.erase(chd_val.begin()+rm);
      assert(sz(chd_val)==2);
      // for(auto [mx,mn]:chd_val)cout<<"("<<mx<<","<<mn<<")";
      // cout<<endl;
      if(val[v]=='+'){
        ret=pii(0,0);
        for(auto [mx,mn]:chd_val)ret.first+=mx,ret.second+=mn;
      }else if(val[v]=='-'){
        //4~8通りしかない
        rep(i,0,sz(chd_val)){
          //iだけmin,他max
          int mnx=chd_val[i].second;
          //iだけmax,他min
          int mxn=chd_val[i].first;
          //iのところだけ+
          rep(j,0,sz(chd_val)){
            if(j==i)continue;
            mnx-=chd_val[j].first;
            mxn-=chd_val[j].second;
          }
          ret.first=max(ret.first,mxn);
          ret.second=min(ret.second,mnx);
        }
      }

      if(G[v][rm]!=p)dfs2(dfs2,G[v][rm],v,ret);
    }    

    // cout<<"頂点"<<v<<" "<<val[v]<<endl;
    // cout<<dp[v].first<<" "<<dp[v].second<<endl;

    return dp[v];
  };
  dfs2(dfs2,root.idx,-1,ini);
  cout<<ans<<endl;
  return 1;
}
accuracy: 1
time_ms: 30
memory_kb: 17560
final_rank: 1

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

struct node {
    char c;
    vector<bool> vtd = vector<bool>(3,false);
    vector<int> mx = vector<int>(3,0);
    vector<int> mn = vector<int>(3,0);
    int num;
    vector<int> to;
};

void solve(string s){
    vector<node> g(4);
    stack<int> st;
    st.push(3);st.push(0);st.push(2);st.push(0);st.push(1);
    
    g[0].to.push_back(1);g[0].to.push_back(2);g[0].to.push_back(3);
    g[1].to.push_back(0);g[2].to.push_back(0);g[3].to.push_back(0);

    for (auto p:s){
        if ('0' <= p && p <= '9'){
            int v = st.top();
            st.pop();
            g[v].num = p - '0';
            g[v].c = '.';
        }
        else if (p == '-' || p == '+'){
            int v = st.top();
            st.pop();
            g[v].c = p;
        }
        else if (p == '(') {
            int v = st.top();
            st.pop();
            node nd;
            g.push_back(nd);
            g.push_back(nd);
            st.push(g.size()-1);
            st.push(v);
            st.push(g.size()-2);
            g[v].to.push_back(g.size()-1);
            g[v].to.push_back(g.size()-2);
            g[g.size()-1].to.push_back(v);
            g[g.size()-2].to.push_back(v);
        }
    }


    int n = g.size();
    int ans = -1e9;
    vector<vector<int>> mx(n, vector<int>(3));
    vector<vector<int>> mn(n, vector<int>(3));
    vector<vector<bool>> vtd(n, vector<bool>(3,false));

    /*for (int i = 0; i < n; i++){
        cout << i << ' ' << g[i].c << ' ';
        if (g[i].c == '.')cout << g[i].num;
        cout << endl;
        for (auto a:g[i].to)cout << a << ' ';
        cout << endl;
    }*/


    auto f = [&](auto &f, int now, int from)->void{
        if (g[now].c == '.'){
            for (int i = 0; i < 3; i++){
                mx[now][i] = g[now].num;
                mn[now][i] = g[now].num;
                vtd[now][i] = true;
            }
            return;
        }

        int idx;
        int v1,v2;
        if (g[now].to[0] == from){
            v1 = g[now].to[1];
            v2 = g[now].to[2];
            idx = 0;
        }
        else if (g[now].to[1] == from){
            v1 = g[now].to[0];
            v2 = g[now].to[2];
            idx = 1;
        }
        else {
            v1 = g[now].to[0];
            v2 = g[now].to[1];
            idx = 2;
        }

        if (vtd[now][idx])return;




        int idx1,idx2;
        for (int i = 0; i < 3; i++){
            if (g[v1].to[i] == now)idx1 = i;
            if (g[v2].to[i] == now)idx2 = i;
        }
        
        f(f,v1,now);
        f(f,v2,now);


        int mx1,mx2,mn1,mn2;
        mx1 = mx[v1][idx1];
        mx2 = mx[v2][idx2];
        mn1 = mn[v1][idx1];
        mn2 = mn[v2][idx2];

        if (g[now].c == '+'){
            mx[now][idx] = mx1 + mx2;
            mn[now][idx] = mn1 + mn2;
        }
        else {
            mx[now][idx] = max(mx1-mn2, mx2-mn1);
            mn[now][idx] = min(mn1-mx2, mn2-mx1);
        }
        vtd[now][idx] = true;
    };

    for (int i = 0; i < n; i++){
        if (g[i].c == '.')continue;

        int i1,i2,i3,j1,j2,j3;
        i1 = g[i].to[0];
        f(f, i1, i);
        for (int j = 0; j < 3; j++){
            if (g[i1].to[j] == i)j1 = j;
        }

        i2 = g[i].to[1];
        f(f, i2, i);
        for (int j = 0; j < 3; j++){
            if (g[i2].to[j] == i)j2 = j;
        }

        i3 = g[i].to[2];
        f(f, i3, i);
        for (int j = 0; j < 3; j++){
            if (g[i3].to[j] == i)j3 = j;
        }

        if (g[i].c == '+')ans = max(ans, mx[i1][j1] + mx[i2][j2] + mx[i3][j3]);
        else {
            ans = max(ans, mx[i1][j1]-mn[i2][j2]-mn[i3][j3]);
            ans = max(ans, mx[i2][j2]-mn[i1][j1]-mn[i3][j3]);
            ans = max(ans, mx[i3][j3]-mn[i2][j2]-mn[i1][j1]);

            //cout << mx[i1][j1]-mn[i2][j2]-mn[i3][j3] << ' ' << mx[i2][j2]-mn[i1][j1]-mn[i3][j3] << ' ' << mx[i3][j3]-mn[i2][j2]-mn[i1][j1] << endl;
        }
        //cout << g[i].c << ' ' << i << endl;
    }
    cout << ans << endl;
}

int main(){
    string s;cin >> s;
    while(s != "-1"){
        solve(s);
        cin >> s;
    }
}
accuracy: 1
time_ms: 100
memory_kb: 91524
final_rank: 19

code_snippet: #include <bits/stdc++.h>
using namespace std;
#define ll long long
#define pii pair<int, int>
#define pll pair<ll, ll>
#define vi vector<int>
#define vl vector<ll>
#define ov4(a, b, c, d, name, ...) name
#define rep3(i, a, b, c) for(ll i = (a); i < (b); i += (c))
#define rep2(i, a, b) rep3(i, a, b, 1)
#define rep1(i, n) rep2(i, 0, n)
#define rep0(n) rep1(aaaaa, n)
#define rep(...) ov4(__VA_ARGS__, rep3, rep2, rep1, rep0)(__VA_ARGS__)
#define per(i, a, b) for(ll i = (a)-1; i >= (b); i--)
#define fore(e, v) for(auto&& e : v)
#define all(a) begin(a), end(a)
#define sz(a) (int)(size(a))
#define lb(v, x) (lower_bound(all(v), x) - begin(v))
#define eb emplace_back

template<typename T, typename S> bool chmin(T& a, const S& b) { return a > b ? a = b, 1 : 0; }
template<typename T, typename S> bool chmax(T& a, const S& b) { return a < b ? a = b, 1 : 0; }
 
const int INF = 1e9 + 100;
const ll INFL = 3e18 + 100;
 
#define i128 __int128_t
 
struct _ {
   _() { cin.tie(0)->sync_with_stdio(0), cout.tie(0); }
} __;

void debug(auto ...vs) {
    ((cerr << vs << " "), ...) << endl;
}

// digit = 1 | 2 | ...
// root = f op f op f
// f = (f op f) | digit

void solve(string s) {
    int m = sz(s);
    
    int n = 0;
    vector<pii> E;
    vector<int> op;
    auto digit = [&](int &i) -> int {
        int x = n++;
        op.emplace_back(-1);
        // debug(x, sz(op));
        op[x] = s[i] - '0';
        i++;
        return x;
    };
    auto f = [&](auto self, int &i) -> int {
        if (s[i] == '(') {
            int x = n++;
            op.emplace_back(-1);
            i++;
            int v = self(self, i);
            E.emplace_back(x, v);
            op[x] = (s[i] == '+');
            i++;// op
            v = self(self, i);
            E.emplace_back(x, v);
            i++;// )
            return x;
        }
        else {
            return digit(i);
        }
    };

    auto root = [&](int &i) -> int {
        int x = n++;
        op.emplace_back(-1);
        
        int v = f(f, i);
        E.emplace_back(x, v);
        // debug(x, v);
        // L
        op[x] = (s[i] == '+');
        i++; // op
        v = f(f, i);
        E.emplace_back(x, v);
        // debug(x, v);
        i++; // op
        v = f(f, i);
        E.emplace_back(x, v);
        // debug(x, v);

        return x;
    };
    
    int pos = 0;
    root(pos);
    // cout << pos << endl;
    // cout << n << endl;
    vector<vi> g(n);
    for(auto [p, q] : E ) {
        g[p].emplace_back(q);
        g[q].emplace_back(p);
        // debug(p, q);
    }

    // rep(i, n) {
    //     debug(sz(g[i]), op[i]);
    // }
    using S = array<int, 2>;
    map<pii, S> mp;
    auto dfs2 = [&](auto self, int v, int p) -> S {
        if (sz(g[v]) == 1) return {op[v], op[v]};
        if (mp.contains(pii{v, p})) return mp[pii{v, p}];
        S ans = {-INF, INF};
        vector<S> res;
        fore(u, g[v]) {
            if (u == p) continue;
            S a;
            a = self(self, u, v);
            res.emplace_back(a);
        }

        if (op[v]) {
            return mp[pii{v, p}] = {res[0][0] + res[1][0], res[0][1] + res[1][1]};
        }
        else {
            return mp[pii{v, p}] = {max(res[0][0] - res[1][1], res[1][0] - res[0][1]) , min(res[0][1] - res[1][0], res[1][1] - res[0][0])};
        }
    };
    
    auto dfs1 = [&](int v) -> int {
        vector<S> res;
        fore(u, g[v]) {
            res.emplace_back(dfs2(dfs2, u, v));
        }
        int ans = -INF;
        if (op[v]) {
            chmax(ans, res[0][0] + res[1][0] + res[2][0]);
        }
        else {
            chmax(ans, res[0][0] - res[1][1] - res[2][1]);
            chmax(ans, res[1][0] - res[2][1] - res[0][1]);
            chmax(ans, res[2][0] - res[0][1] - res[1][1]);
        }
        return ans;
    };

    // rep(i, n) {
    //     if (sz(g[i]) == 1) {

    //     }
    // }
    int ans = -INF;
    rep(i, n) {
        if (sz(g[i]) == 3) {
            chmax(ans, dfs1(i));
        }
    }
    cout << ans << endl;
}


int main() {

    // int T;cin >> T;
	int T = 1;
    while(true) {
        string s;cin >> s;
        if (s == "-1") break;
        solve(s);
    }
    
}
accuracy: 1
time_ms: 90
memory_kb: 29920
final_rank: 13

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

using ll = long long;
using pii = pair<int, int>;
using pll = pair<ll, ll>;
using vi = vector<int>;
using vl = vector<ll>;
#define rep3(i, a, b, c) for (ll i = (a); i < (b); i += (c))
#define rep2(i, a, b) rep3(i, a, b, 1)
#define rep1(i, n) rep2(i, 0, n)
#define rep0(n) rep1(aaaaa, n)
#define ov4(a, b, c, d, name, ...) name
#define rep(...) ov4(__VA_ARGS__, rep3, rep2, rep1, rep0)(__VA_ARGS__)
#define per(i, a, b) for (ll i = (a) - 1; i >= (b); i--)
#define fore(e, v) for (auto&& e : v)
#define all(a) begin(a), end(a)
#define sz(a) (int)(size(a))
#define lb(v, x) (lower_bound(all(v), x) - begin(v))
#define eb emplace_back

template <typename T, typename S>
bool chmin(T& a, const S& b) {
  return a > b ? a = b, 1 : 0;
}
template <typename T, typename S>
bool chmax(T& a, const S& b) {
  return a < b ? a = b, 1 : 0;
}
const int INF = 1e9 + 100;
const ll INFL = 3e18 + 100;
#define i128 __int128_t
struct _ {
  _() { cin.tie(0)->sync_with_stdio(0), cout.tie(0); }
} __;

void solve(string);
int main(){
  while(1){
    string S;
    cin>>S;
    if(S=="-1")break;
    solve(S);
  }
}

void solve(string VS){
  using vpii =  vector<pii>;
  vector<vector<pii>> G;

  vector<char> GC;
  G.reserve(sz(VS));
  GC.reserve(sz(VS));

  // lから1フレーズ (vertex,right)
  auto lex=[&G,&GC](auto f,int l,const string& s,bool top=false) -> pair<int,int> {
    if(top){
      if(s[l]=='('){
        auto [v,r]=f(f,l+1,s);
        return pii{v,-1};
      }else{
        int v=sz(G);
        G.push_back(vpii());
        GC.push_back(s[l]);
        return pii{v,-1};
      }
    }
    int v1=-1,v2=-1;
    if(s[l]=='('){
      auto [v,r]=f(f,l+1,s);
      v1=v;
      l=r +1; // ')'
    }else{
      v1=sz(G);
      G.push_back(vpii());
      GC.push_back(s[l]);
    }
    l++;
    int vp=sz(GC);
    G.push_back(vpii());
    GC.push_back(s[l]);
    l++;
    if(s[l]=='('){
      auto [v,r]=f(f,l+1,s);
      v2=v;
      l=r+1; // ')'
    }else{
      v2=sz(G);
      G.push_back(vpii());
      GC.push_back(s[l]);
    }
    G[v1].push_back(pii{vp,sz(G[vp])});
    G[vp].push_back(pii{v1,sz(G[v1])-1});
    G[v2].push_back(pii{vp,sz(G[vp])});
    G[vp].push_back(pii{v2,sz(G[v2])-1});
    return pii{vp,l};
  };

  // 1
  string T1="";
  int dep=0,l=0;
  for(;l<sz(VS);l++){
    if(VS[l]=='(')dep++;
    if(VS[l]==')')dep--;
    T1+=VS[l];
    if(dep==0)break;
  }
  auto [v1,uuuuuuu]=lex(lex,0,T1,true);
  l++;
  char cp=VS[l];
  l++;
  // 2
  string T2="";
  for(;l<sz(VS);l++){
    if(VS[l]=='(')dep++;
    if(VS[l]==')')dep--;
    T2+=VS[l];
    if(dep==0)break;
  }
  auto [v2,uuuuuuuu]=lex(lex,0,T2,true);
  l+=2;
  // 3
  string T3="";
  for(;l<sz(VS);l++){
    if(VS[l]=='(')dep++;
    if(VS[l]==')')dep--;
    T3+=VS[l];
    if(dep==0)break;
  }
  auto [v3,uuuuuu]=lex(lex,0,T3,true);
  int vp=sz(G);

  // cerr<<T1<<' '<<T2<<' '<<T3<<' '<<cp<<endl;
  G.push_back(vpii());
  GC.push_back(cp);
  G[vp].push_back(pii{v1,sz(G[v1])});
  G[v1].push_back(pii{vp,sz(G[vp])-1});
  G[vp].push_back(pii{v2,sz(G[v2])});
  G[v2].push_back(pii{vp,sz(G[vp])-1});
  G[vp].push_back(pii{v3,sz(G[v3])});
  G[v3].push_back(pii{vp,sz(G[vp])-1});

  int N=sz(G);
  // cerr<<"N:"<<N<<endl;

  // fore(i,GC)cerr<<i<<' ';
  // cerr<<endl;
  // rep(i,N){
  //   cerr<<"v:"<<i<<endl;
  //   fore(j,G[i])cerr<<j.first<<'/'<<j.second<<' ';
  //   cerr<<endl;
  // }
  // cerr<<endl;
  


  // (max,min)
  vector dp(N,vector<pii>());
  rep(i,N){
    dp[i].resize(sz(G[i]));
    fore(j,dp[i]){
      j=pii{-1e9,1e9};
    }
  }

  auto dfs=[&](auto f,int v,int p) -> pii {
    auto &g=G[v];
    rep(i,sz(g)){
      if(g[i].first==p)continue;
      dp[v][i]=f(f,g[i].first,v);
    }
    if(GC[v]=='+'){
      array<int,3> a,b;
      rep(i,sz(g)){
        a[i]=dp[v][i].first;
        b[i]=dp[v][i].second;
      }
      pii ret{-1e9,1e9};
      rep(i,3){
        rep(j,i+1,3){
          if(a[i]==-1e9||a[j]==-1e9)continue;
          chmax(ret.first,a[i]+a[j]);
          chmin(ret.second,b[i]+b[j]);
        }
      }
      return ret;
    }else if(GC[v]=='-'){
      array<int,3> a,b;
      rep(i,sz(g)){
        a[i]=dp[v][i].first;
        b[i]=dp[v][i].second;
      }
      pii ret{-1e9,1e9};
      rep(i,3){
        rep(j,3){
          if(a[i]==-1e9||a[j]==-1e9||i==j)continue;
          chmax(ret.first,a[i]-b[j]);
          chmin(ret.second,b[i]-a[j]);
        }
      }
      return ret;
    }else{
      int x=GC[v]-'0';
      return pii{x,x};
    }
  };

  dfs(dfs,vp,-1);

  // rep(i,N){
  //   cerr<<"v:"<<i<<endl;
  //   fore(j,dp[i])cerr<<j.first<<'/'<<j.second<<' ';
  //   cerr<<endl;
  // }
  // cerr<<endl;

  auto dfs2=[&](auto f,int v,int p) -> void {
    auto &g=G[v];
    // leaf
    if(sz(g)==1)return;
    
    rep(x,sz(g)){
      pii a,b;
      int c=0;
      rep(j,sz(g)){
        if(j!=x){
          if(c==0)a=dp[v][j],c++;
          else if(c==1) b=dp[v][j];
        }
      }
      if(GC[v]=='+'){
        dp[g[x].first][g[x].second]=pii{a.first+b.first,a.second+b.second};
      }else if(GC[v]=='-'){
        dp[g[x].first][g[x].second]=pii{
          max(a.first-b.second,b.first-a.second),
          min(a.second-b.first,b.second-a.first)
        };
      }else{
        assert(false);
      }
    }
    rep(i,sz(g)){
      if(g[i].first!=p)f(f,g[i].first,v);
    }
    return;
  };

  dfs2(dfs2,vp,-1);

  // rep(i,N){
  //   cerr<<"v:"<<i<<endl;
  //   fore(j,dp[i])cerr<<j.first<<'/'<<j.second<<' ';
  //   cerr<<endl;
  // }

  int ans=-1e9;
  rep(i,N){
    if(GC[i]=='+'){
      int now=0;
      for(auto j:dp[i]){
        now+=j.first;
      }
      chmax(ans,now);
    }else if(GC[i]=='-'){
      int s=0,f=-1e9;
      for(auto j:dp[i]){
        s-=j.second;
        chmax(f,j.first+j.second);
      }
      chmax(ans,f+s);
    }
  }
  cout<<ans<<'\n';
}
accuracy: 1
time_ms: 30
memory_kb: 28812
final_rank: 7

code_snippet: #include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define rep(i, s, t) for (ll i = s; i < (ll)(t); i++)
#define rrep(i, s, t) for(ll i = (ll)(t) - 1; i >= (ll)(s); i--)
#define all(x) begin(x), end(x)
#define rall(x) rbegin(x), rend(x)

#define TT template<typename T>
TT using vec = vector<T>;
template<class T1, class T2> bool chmin(T1 &x, T2 y) { return x > y ? (x = y, true) : false; }
template<class T1, class T2> bool chmax(T1 &x, T2 y) { return x < y ? (x = y, true) : false; }

struct io_setup {
    io_setup() {
        ios::sync_with_stdio(false);
        std::cin.tie(nullptr);
        cout << fixed << setprecision(15);
    }
} io_setup;

int solve(){
    string s;
    cin>>s;
    if(s=="-1") return 0;
    vector<vector<int>> vp;
    int cnt=0;
    vector<int> dat;
    {
        vector<pair<int,int>> g;
        auto f=[&](auto self,int &i) -> int {
            if(s[i]=='('){
                i++;
                int a = self(self,i);
                char c = s[i];
                assert(c=='+'||c=='-');
                i++;
                int b = self(self,i);
                assert(s[i]==')');
                i++;
                if(c=='+') dat.push_back(10);
                else dat.push_back(-10);
                g.push_back({cnt,a});
                g.push_back({cnt,b});
            }else{
                dat.push_back(s[i]-'0');
                i++;
            }
            return cnt++;
        };
        int i=0;
        char c;
        {
            int x = f(f,i);
            c=s[i];
            i++;
            int y = f(f,i);
            assert(s[i]==c);
            i++;
            int z = f(f,i);
            g.push_back({cnt,x});
            g.push_back({cnt,y});
            g.push_back({cnt,z});
            if(c=='+') dat.push_back(10);
            else dat.push_back(-10);
            cnt++;
        }
        vp.resize(cnt);
        for(auto[x,y]:g){
            vp[x].push_back(y);
            vp[y].push_back(x);
        }
    }
    auto checkv=[&](vector<ll> vmx,vector<ll> vmn) ->pair<ll,ll> {
        int m=vmx.size();
        ll tmx=0,tmn=0;
        rep(i,0,m){
            tmx+=vmx[i];
            tmn+=vmn[i];
        }
        ll mx=-1e18,mn=1e18;
        rep(i,0,m){
            chmax(mx,-(tmn-vmn[i])+vmx[i]);
            chmin(mn,-(tmx-vmx[i])+vmn[i]);
        }
        return {mx,mn};
    };
    vector<ll> mx(cnt),mn(cnt);
    {
        auto dfs=[&](auto self,int nw,int pr) ->void {
            if(abs(dat[nw])<10){
                mx[nw]=mn[nw]=dat[nw];
                return;
            }
            if(dat[nw]>0){
                ll tmx=0,tmn=0;
                for(int nx:vp[nw]){
                    if(nx==pr) continue;
                    self(self,nx,nw);
                    tmx+=mx[nx];
                    tmn+=mn[nx];
                }
                mx[nw]=tmx;
                mn[nw]=tmn;
            }else{
                vector<ll> vmx,vmn;
                for(int nx:vp[nw]){
                    if(nx==pr) continue;
                    self(self,nx,nw);
                    vmx.push_back(mx[nx]);
                    vmn.push_back(mn[nx]);
                }        
                auto[tmx,tmn]=checkv(vmx,vmn);
                mx[nw]=tmx;
                mn[nw]=tmn;
            }
        };
        dfs(dfs,cnt-1,-1);
    }
    ll ans=-1e18;
    {
        ll bmx=0,bmn=0;
        auto dfs=[&](auto self,int nw,int pr){
            if(abs(dat[nw])<10) return;
            vector<ll> vmx,vmn;
            for(int nx:vp[nw]){
                if(nx==pr) continue;
                vmx.push_back(mx[nx]);
                vmn.push_back(mn[nx]);
            }
            if(pr!=-1){
                vmx.push_back(bmx);
                vmn.push_back(bmn);
            }
            if(dat[nw]>0){
                ll tmx=0;
                for(auto x:vmx) tmx+=x;
                chmax(ans,tmx);
            }else{
                assert(vmx.size()==3);
                auto[tmx,tmn]=checkv(vmx,vmn);
                chmax(ans,tmx);
            }
            if(dat[nw]>0){
                ll tmx=0,tmn=0;
                for(auto x:vmx) tmx+=x;
                for(auto x:vmn) tmn+=x;
                for(int nx:vp[nw]){
                    if(nx==pr) continue;
                    bmx=tmx-mx[nx];
                    bmn=tmn-mn[nx];
                    self(self,nx,nw);
                }
            }else{
                int ctt=0;
                for(int nx:vp[nw]){
                    if(nx==pr) continue;
                    auto cmv=vmx;
                    cmv.erase(cmv.begin()+ctt);
                    auto cnv=vmn;
                    cnv.erase(cnv.begin()+ctt);
                    assert(cmv.size()==2);
                    auto[tmx,tmn]=checkv(cmv,cnv);
                    bmx=tmx;
                    bmn=tmn;
                    self(self,nx,nw);
                    ctt++;
                }
            }
        };
        dfs(dfs,cnt-1,-1);
    }
    cout<<ans<<"\n";
    return 1;
}

int main() {
    while(solve());
}
accuracy: 1
time_ms: 50
memory_kb: 18656
final_rank: 4

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

using ll = long long;

using pii = std::pair<int, int>;

template <class T>
bool chmax(T& x, const T& v) {
  if (x < v) {
    x = v;
    return true;
  } else {
    return false;
  }
}
template <class T>
bool chmin(T& x, const T& v) {
  if (x > v) {
    x = v;
    return true;
  } else {
    return false;
  }
}

struct tree;

using pointer = std::shared_ptr<tree>;

struct tree {
  char op;
  ll min, max;
  bool cached = false;
  bool rooted = false;

  std::vector<pointer> children;

  tree(char op, pointer l, pointer r) : op(op), children({l, r}) {}
  tree(char op, pointer l, pointer m, pointer r)
      : op(op), children({l, m, r}), rooted(true) {}

  tree(ll val) : min(val), max(val), cached(true) {}

  void calc() {
    if (cached) {
      return;
    }

    for (auto ch : children) {
      ch->calc();
    }

    if (op == '+') {
      max = min = 0;
      for (auto ch : children) {
        max += ch->max;
        min += ch->min;
      }
    } else {
      max = std::numeric_limits<ll>::min();
      min = std::numeric_limits<ll>::max();

      for (int i = 0; i < children.size(); i++) {
        ll tmpmax = children[i]->max, tmpmin = children[i]->min;

        for (int k = 0; k < children.size(); k++) {
          if (i == k) continue;

          tmpmax -= children[k]->min;
          tmpmin -= children[k]->max;
        }

        chmax(max, tmpmax);
        chmin(min, tmpmin);
      }
    }

    cached = true;
  }

  void force_calc() {
    cached = false;
    calc();
  }

  static pointer rotate_at(pointer root, int i) {
    pointer l = root->children[i];

    root->children.erase(root->children.begin() + i);

    root->force_calc();

    l->children.push_back(root);

    l->force_calc();

    l->rooted = true;

    return l;
  }
};

void debug_(pointer root, std::string& str) {
  if (root->children.size()) {
    str.push_back('(');

    for (int i = 0; i < root->children.size(); i++) {
      if (i > 0) {
        str.push_back(root->op);
      }
      debug_(root->children[i], str);
    }

    str.push_back(')');

  } else {
    str.push_back('0' + root->max);
  }
}

std::string debug(pointer root) {
  std::string str;

  debug_(root, str);

  return str;
}

pointer parse(const std::string& str, int& pos) {
  if (std::isalnum(str[pos])) {
    return std::make_shared<tree>(str[pos++] - '0');
  } else {
    if (str[pos++] != '(') {
      std::cerr << "error! " << str[pos - 1] << '\n';
    };
    pointer l = parse(str, pos);
    char op = str[pos++];
    pointer r = parse(str, pos);
    assert(str[pos++] == ')');
    return std::make_shared<tree>(op, l, r);
  }
}

pointer parse_root(const std::string& str, int& pos) {
  pointer l = parse(str, pos);
  char op = str[pos++];
  pointer m = parse(str, pos);
  assert(op == str[pos++]);
  pointer r = parse(str, pos);
  assert(pos == str.size());

  return std::make_shared<tree>(op, l, m, r);
}

ll traverse(pointer root) {
  root->calc();

  ll res = root->max;

  // std::println(std::cerr, "{}", debug(root));

  // std::println(std::cerr, "size of tree: {}", root->children.size());

  while (true) {
    bool rotated = false;

    for (int i = 0; i < 3; i++) {
      if (root->children[i]->children.size() && !root->children[i]->rooted) {
        pointer tmp = tree::rotate_at(root, i);

        // assert(root->children.size() == 2);
        // assert(tmp->children.size() == 3);

        rotated = true;
        chmax(res, traverse(tmp));

        bool is_ok = false;

        for (int k = 0; k < 3; k++) {
          if (tmp->children[k] == root) {
            tree::rotate_at(tmp, k);
            is_ok = true;
            break;
          }
        }

        assert(is_ok);

        assert(root->children.size() == 3);

        break;
      }
    }

    if (!rotated) {
      break;
    }
  }

  return res;
}

bool solve() {
  std::string S;
  std::cin >> S;
  int pos = 0;

  if (S == "-1") {
    return false;
  }

  pointer root = parse_root(S, pos);

  std::cout << traverse(root) << '\n';

  return true;
}

int main() {
  while (solve());
}
accuracy: 1
time_ms: 30
memory_kb: 31840
final_rank: 10

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

/* ATCODER
#include<atcoder/all>
using namespace atcoder;
typedef modint998244353 mint;
//*/

/* BOOST MULTIPRECISION
#include<boost/multiprecision/cpp_int.hpp>
using namespace boost::multiprecision;
//*/

typedef long long ll;

#define rep(i, s, n) for (int i = (int)(s); i < (int)(n); i++)
#define rrep(i, s, n) for (int i = (int)(n)-1; i >= (int)(s); i--)
#define all(v) begin(v),end(v)

template <typename T> bool chmin(T &a, const T &b) {
	if (a <= b) return false;
	a = b;
	return true;
}

template <typename T> bool chmax(T &a, const T &b) {
	if (a >= b) return false;
	a = b;
	return true;
}

template <typename T> T max(vector<T> &a){
	assert(!a.empty());
	T ret = a[0];
	for (int i=0; i<(int)a.size(); i++) chmax(ret, a[i]);
	return ret;
}

template <typename T> T min(vector<T> &a){
	assert(!a.empty());
	T ret = a[0];
	for (int i=0; i<(int)a.size(); i++) chmin(ret, a[i]);
	return ret;
}

template <typename T> T sum(vector<T> &a){
	T ret = 0;
	for (int i=0; i<(int)a.size(); i++) ret += a[i];
	return ret;
}

string s;
vector<vector<int>> ikeru;
vector<int> is_leaf;
int piv = 0;
vector<int> st;

void pars();
void childs();

void pars() {

    st.push_back(0);
    ikeru.push_back(vector<int>(0));
    is_leaf.push_back(-1);

    childs();
    char c = s[piv];
    assert(c == '+' || c == '-');
    is_leaf[st.back()] = (c == '+' ? -1 : -2);
    piv++;

    childs();
    piv++;
    childs();

    st.pop_back();

}

void childs() {
    if ('0' <= s[piv] && s[piv] <= '9') {
        is_leaf.push_back(s[piv] - '0');
        ikeru.push_back(vector<int>(0));
        st.push_back((int)is_leaf.size() - 1);

        ikeru[st[(int)st.size()-1]].push_back(st[(int)st.size()-2]);
        ikeru[st[(int)st.size()-2]].push_back(st[(int)st.size()-1]);
        piv++;

        st.pop_back();
        return;
    }

    ikeru.push_back(vector<int>(0));
    is_leaf.push_back(-1);
    st.push_back((int)is_leaf.size() - 1);

    ikeru[st[(int)st.size()-1]].push_back(st[(int)st.size()-2]);
    ikeru[st[(int)st.size()-2]].push_back(st[(int)st.size()-1]);


    assert(s[piv] == '(');
    piv++;

    childs();

    char c = s[piv];
    assert(c == '+' || c == '-');
    is_leaf[st.back()] = (c == '+' ? -1 : -2);
    piv++;

    childs();

    assert(s[piv] == ')');
    piv++;

    st.pop_back();
}


void solve() {
    ikeru.clear();
    is_leaf.clear();
    piv=0;
    st.clear();
    // root = 0
    pars();

    /*
    rep(i,0,(int)is_leaf.size()) {
        cout << is_leaf[i] << ' ';
    }
    cout << endl;
    */


    map<pair<int,int>,pair<ll,ll>> mp;
    auto dfs = [&](auto self, int i, int p) -> pair<ll,ll> {
        if(mp.find(pair(p, i)) != mp.end()) {
            return mp[pair(p, i)];
        }
        ll maxval = -1e9, minval = 1e9;
        if (is_leaf[i] >= 0) {
            maxval = is_leaf[i];
            minval = is_leaf[i];
        }else{
            vector<pair<ll,ll>> values;
            for (int j: ikeru[i]) {
                if (j == p) continue;
                values.push_back(self(self, j, i));
                //cout << i << ' ' << j << ' ' << self(self,j,i).first << ' ' << self(self,j,i).second << endl;
            }

            if (is_leaf[i] == -1) {
                minval = 0;
                maxval = 0;
                rep(j,0,(int)values.size()) {
                    minval += values[j].first;
                    maxval += values[j].second;
                }
            }else {
                ll tmpmin = 0, tmpmax = 0;
                rep(j,0,(int)values.size()) {
                    tmpmin -= values[j].second;
                    tmpmax -= values[j].first;
                }
                rep(j,0,(int)values.size()) {
                    chmin(minval, tmpmin + values[j].second + values[j].first);
                    chmax(maxval, tmpmax + values[j].second + values[j].first);
                }
            }
            
        }
        mp[pair(p, i)] = pair(minval, maxval);
        return pair(minval, maxval);
    };

    int n = is_leaf.size();
    ll ans = -1e9;
    rep(st,0,n) {
        if (is_leaf[st] >= 0) continue;
        dfs(dfs, st, st);
        chmax(ans, mp[pair(st,st)].second);
    }
    cout << ans << '\n';

}

int main() {
	while(true){
        cin >> s;
        if (s == "-1") break;
        solve();
	}
}
accuracy: 1
time_ms: 140
memory_kb: 41128
final_rank: 16

code_snippet: #include <iostream>
#include <vector>
#include <algorithm>
#include <utility>
#include <array>
using namespace std;
using ll = long long;
#define rep(i,n) for(ll i=0; i<ll(n); i++)
template<class A, class B> void chmax(A& a, const B& b){ if(a < b) a = b; }
template<class A, class B> void chmin(A& a, const B& b){ if(b < a) a = b; }

void testcase(){
    string s; cin >> s;
    if(s == "-1") exit(0);
    vector<vector<ll>> adj;
    vector<ll> val;
    auto newNode = [&]() -> ll {
        ll res = adj.size();
        adj.push_back({});
        val.push_back(-1);
        return res;
    };
    auto addEdge = [&](ll u, ll v){
        adj[u].push_back(v);
        adj[v].push_back(u);
    };
    auto readNonRoot = [&](auto& readNonRoot, ll& p) -> ll {
        ll q = newNode();
        if(s[p] == '('){
            p++;
            auto a = readNonRoot(readNonRoot, p);
            val[q] = s[p++];
            auto b = readNonRoot(readNonRoot, p);
            addEdge(q,a);
            addEdge(q,b);
            p++;
        } else {
            val[q] = s[p++];
        }
        return q;
    };
    auto readRoot = [&]() -> ll {
        ll p = 0;
        ll q = newNode();
        auto a = readNonRoot(readNonRoot, p);
        val[q] = s[p++];
        auto b = readNonRoot(readNonRoot, p);
        s[p++];
        auto c = readNonRoot(readNonRoot, p);
        addEdge(q,a);
        addEdge(q,b);
        addEdge(q,c);
        return q;
    };
    readRoot();

    ll N = adj.size();
    vector<array<ll, 3>> ql(N), qr(N);
    rep(i,N) rep(j,3) ql[i][j] = 1ll << 60;
    rep(i,N) rep(j,3) qr[i][j] = -(1ll << 60);

    auto dfs = [&](auto& dfs, ll v, ll w) -> pair<ll, ll> {
        if(val[v] != '+' && val[v] != '-') return { val[v] - '0', val[v] - '0' };
        ll i = 0; while(adj[v][i] != w) i++;
        if(ql[v][i] != (1ll << 60)) return { ql[v][i], qr[v][i] };
        auto [a1, b1] = dfs(dfs, adj[v][(i+1)%3], v);
        auto [a2, b2] = dfs(dfs, adj[v][(i+2)%3], v);
        if(val[v] == '+'){
            ql[v][i] = a1 + a2;
            qr[v][i] = b1 + b2;
        } else {
            ql[v][i] = min(a1 - b2, a2 - b1);
            qr[v][i] = max(b1 - a2, b2 - a1);
        }
        return { ql[v][i], qr[v][i] };
    };

    ll ans = -(1ll << 60);
    rep(i,N) if(val[i] == '+' || val[i] == '-'){
        auto [a1, b1] = dfs(dfs, adj[i][0], i);
        auto [a2, b2] = dfs(dfs, adj[i][1], i);
        auto [a3, b3] = dfs(dfs, adj[i][2], i);
        if(val[i] == '+'){
            chmax(ans, b1 + b2 + b3);
        } else {
            chmax(ans, b1 - a2 - a3);
            chmax(ans, b2 - a1 - a3);
            chmax(ans, b3 - a2 - a1);
        }
    }
    cout << ans << "\n";
}

int main(){
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    while(true) testcase();
    return 0;
}
accuracy: 1
time_ms: 20
memory_kb: 28144
final_rank: 5

code_snippet: #include <iostream>
#include <vector>
#include <algorithm>
#include <utility>
#include <array>
using namespace std;
using ll = long long;
#define rep(i,n) for(ll i=0; i<ll(n); i++)
template<class A, class B> void chmax(A& a, const B& b){ if(a < b) a = b; }
template<class A, class B> void chmin(A& a, const B& b){ if(b < a) a = b; }

void testcase(){
    string s; cin >> s;
    if(s == "-1") exit(0);
    vector<vector<ll>> adj;
    vector<ll> val;
    auto newNode = [&]() -> ll {
        ll res = adj.size();
        adj.push_back({});
        val.push_back(-1);
        return res;
    };
    auto addEdge = [&](ll u, ll v){
        adj[u].push_back(v);
        adj[v].push_back(u);
    };
    auto readNonRoot = [&](auto& readNonRoot, ll& p) -> ll {
        ll q = newNode();
        if(s[p] == '('){
            p++;
            auto a = readNonRoot(readNonRoot, p);
            val[q] = s[p++];
            auto b = readNonRoot(readNonRoot, p);
            addEdge(q,a);
            addEdge(q,b);
            p++;
        } else {
            val[q] = s[p++];
        }
        return q;
    };
    auto readRoot = [&]() -> ll {
        ll p = 0;
        ll q = newNode();
        auto a = readNonRoot(readNonRoot, p);
        val[q] = s[p++];
        auto b = readNonRoot(readNonRoot, p);
        s[p++];
        auto c = readNonRoot(readNonRoot, p);
        addEdge(q,a);
        addEdge(q,b);
        addEdge(q,c);
        return q;
    };
    readRoot();

    ll N = adj.size();
    vector<array<ll, 3>> ql(N), qr(N);
    rep(i,N) rep(j,3) ql[i][j] = 1ll << 60;
    rep(i,N) rep(j,3) qr[i][j] = -(1ll << 60);

    auto dfs = [&](auto& dfs, ll v, ll w) -> pair<ll, ll> {
        if(val[v] != '+' && val[v] != '-') return { val[v] - '0', val[v] - '0' };
        ll i = 0; while(adj[v][i] != w) i++;
        if(ql[v][i] != (1ll << 60)) return { ql[v][i], qr[v][i] };
        auto [a1, b1] = dfs(dfs, adj[v][(i+1)%3], v);
        auto [a2, b2] = dfs(dfs, adj[v][(i+2)%3], v);
        if(val[v] == '+'){
            ql[v][i] = a1 + a2;
            qr[v][i] = b1 + b2;
        } else {
            ql[v][i] = min(a1 - b2, a2 - b1);
            qr[v][i] = max(b1 - a2, b2 - a1);
        }
        return { ql[v][i], qr[v][i] };
    };

    ll ans = -(1ll << 60);
    rep(i,N) if(val[i] == '+' || val[i] == '-'){
        auto [a1, b1] = dfs(dfs, adj[i][0], i);
        auto [a2, b2] = dfs(dfs, adj[i][1], i);
        auto [a3, b3] = dfs(dfs, adj[i][2], i);
        if(val[i] == '+'){
            chmax(ans, b1 + b2 + b3);
        } else {
            chmax(ans, b1 - a2 - a3);
            chmax(ans, b2 - a1 - a3);
            chmax(ans, b3 - a2 - a1);
        }
    }
    cout << ans << "\n";
}

int main(){
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    while(true) testcase();
    return 0;
}
accuracy: 1
time_ms: 20
memory_kb: 28652
final_rank: 6

code_snippet: #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ull = unsigned long long;
using vll = vector<ll>;
using vvll = vector<vll>;
using P = pair<int, int>;
using PP = pair<int, P>;
using PLL = pair<ll, ll>;
using PPLL = pair<ll, PLL>;
#define rep(i, n) for(ll i = 0; i < n; ++i)
#define rrep(i, n) for(ll i = n - 1; i >= 0; --i)
#define loop(i, a, b) for(ll i = a; i <= b; ++i)
#define all(v) v.begin(), v.end()
#define nC2(n) n * (n - 1) / 2
constexpr ll INF = 9009009009009009009LL;
constexpr int INF32 = 2002002002;
constexpr ll MOD = 998244353;
constexpr ll MOD107 = 1000000007;

// Linear Algebra ////////////////////////////////////////////////
const double Rad2Deg = 180.0 / M_PI;
const double Deg2Rad = M_PI / 180.0;
//////////////////////////////////////////////////////////////////

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

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

template <typename Container,
          typename = std::enable_if_t<
              !std::is_same_v<Container, std::string> &&
              std::is_convertible_v<decltype(std::declval<Container>().begin()),
                                    typename Container::iterator>>>
ostream &operator<<(ostream &os, const Container &container) {
    auto it = container.begin();
    auto end = container.end();

    if (it != end) {
        os << *it;
        ++it;
    }
	for (; it != end; ++it) {
		os << " " << *it;
	}
    return os;
}
template <typename T>
ostream& operator<<(ostream& os, const vector<T>& v) {
    for (size_t i = 0; i < v.size(); ++i) {
        os << v[i];
        if (i != v.size() - 1) os << " ";
    }
    return os;
}
template <typename T>
ostream& operator<<(ostream& os, const vector<vector<T>>& vv) {
	for (size_t i = 0; i < vv.size(); ++i) {
		os << vv[i];
		if (i != vv.size() - 1) os << "\n";
    }
    return os;
}
template <typename T>
istream& operator>>(istream& is, vector<T>& v) {
	assert(v.size() > 0);
	for (size_t i = 0; i < v.size(); ++i) is >> v[i];
	return is;
}
template <typename T>
istream& operator>>(istream& is, vector<vector<T>>& vv) {
	assert(vv.size() > 0);
	for (size_t i = 0; i < vv.size(); ++i) is >> vv[i];
	return is;
}

struct phash {
	template<class T1, class T2>
    inline size_t operator()(const pair<T1, T2> & p) const {
        auto h1 = hash<T1>()(p.first);
        auto h2 = hash<T2>()(p.second);

		size_t seed = h1 + h2; 
		h1 = ((h1 >> 16) ^ h1) * 0x45d9f3b;
        h1 = ((h1 >> 16) ^ h1) * 0x45d9f3b;
        h1 = (h1 >> 16) ^ h1;
        seed ^= h1 + 0x9e3779b9 + (seed << 6) + (seed >> 2);
		h2 = ((h2 >> 16) ^ h2) * 0x45d9f3b;
        h2 = ((h2 >> 16) ^ h2) * 0x45d9f3b;
        h2 = (h2 >> 16) ^ h2;
        seed ^= h2 + 0x9e3779b9 + (seed << 6) + (seed >> 2);
        return seed;
    }
};




struct DP
{
	ll mx;
	ll mn;

    DP(ll mx = -INF, ll mn = INF) : mx(mx), mn(mn) {}

    // 2つのDPをマージ(結合則が成り立つ必要がある)
    /* DP operator+(const DP &rhs) const { return DP(dp + rhs.dp, sum + rhs.sum); }
    DP operator-(const DP &rhs) const { return DP(dp - rhs.dp, sum - rhs.sum); } */
    // 親に辿ったときの値の更新
    // DP up() const { return DP(dp + sum, sum); }
};

DP calculate(vector<DP> children, char op) {
	DP res(-INF, INF);

	vll p;
	rep(i, children.size()) {
		p.push_back(i);
	}
	do {
		rep(ismx, 1 << children.size()) {
			ll ans;
			if (ismx & (1 << 0)) ans = children[p[0]].mx;
			else ans = children[p[0]].mn;

			loop(i, 1, children.size() - 1) {
				if (ismx & (1 << i)) {
					if (op == '+') ans += children[p[i]].mx;
					else ans -= children[p[i]].mx;
				}
				else {
					if (op == '+') ans += children[p[i]].mn;
					else ans -= children[p[i]].mn;
				}
			}

			chmax(res.mx, ans);
			chmin(res.mn, ans);
		}
	}
	while (next_permutation(all(p)));
	return res;
}

int solve() {
	string s;
	cin >> s;
	if (s == "-1") return 1;

	vector<vector<DP>> dp;
	vector<bool> isNode;
	vector<char> ops;
	vvll g;
	vector<PLL> edges;
	auto parse = [&](auto self, int& i, int idx) -> pair<ll, DP> {
		dp.push_back(vector<DP>());
		isNode.push_back(true);
		ops.push_back('\0');
		g.push_back(vll());

		ll nextidx = idx + 1;
		if (s[i] == '(') {
			g[idx].push_back(nextidx);
			edges.push_back({idx, nextidx});
			i++;
			auto [id, val] = self(self, i, nextidx);
			dp[idx].push_back(val);
			nextidx = id + 1;
		}
		else {
			assert('0' <= s[i] && s[i] <= '9');
			g.push_back(vll());
			g[idx].push_back(nextidx);
			edges.push_back({idx, nextidx});
			ll v = s[i] - '0';
			dp.push_back(vector<DP>());
			isNode.push_back(false);
			ops.push_back('\0');
			dp[idx].push_back(DP(v, v));
			nextidx++;
		}

		i++;
		assert(s[i] == '+' || s[i] == '-');
		ops[idx] = s[i];
		i++;

		if (s[i] == '(') {
			g[idx].push_back(nextidx);
			edges.push_back({idx, nextidx});
			i++;
			auto [id, val] = self(self, i, nextidx);
			dp[idx].push_back(val);
			nextidx = id + 1;
		}
		else {
			assert('0' <= s[i] && s[i] <= '9');
			g.push_back(vll());
			g[idx].push_back(nextidx);
			edges.push_back({idx, nextidx});
			ll v = s[i] - '0';
			dp.push_back(vector<DP>());
			isNode.push_back(false);
			ops.push_back('\0');
			dp[idx].push_back(DP(v, v));
			nextidx++;
		}

		i++;
		assert(s[i] == '+' || s[i] == '-' || s[i] == ')');

		if (s[i] == ')') {
			goto calc;
		}

		i++;
		if (s[i] == '(') {
			g[idx].push_back(nextidx);
			edges.push_back({idx, nextidx});
			i++;
			auto [id, val] = self(self, i, nextidx);
			dp[idx].push_back(val);
			nextidx = id + 1;
		}
		else {
			assert('0' <= s[i] && s[i] <= '9');
			g.push_back(vll());
			g[idx].push_back(nextidx);
			edges.push_back({idx, nextidx});
			ll v = s[i] - '0';
			dp.push_back(vector<DP>());
			isNode.push_back(false);
			ops.push_back('\0');
			dp[idx].push_back(DP(v, v));
			nextidx++;
		}

	calc:
		DP res = calculate(dp[idx], ops[idx]);
		return {nextidx - 1, res};
	};

	int i = 0;
	parse(parse, i, 0);

	for (auto [u, v] : edges) {
		g[v].push_back(u);
		dp[v].push_back(DP());
	}

	ll ans = -INF;
    auto bfs = [&](auto bfs, ll v, ll p, DP par) -> void {
        ll deg = g[v].size();
        rep(i, deg) if (g[v][i] == p) dp[v][i] = par;

		vector<DP> all;
		rep(i, deg) {
			all.push_back(dp[v][i]);
		}
		chmax(ans, calculate(all, ops[v]).mx);

        rep(i, deg) {
            if (g[v][i] == p) continue;
			if (!isNode[g[v][i]]) continue;

			vector<DP> children;
			rep(j, deg) {
				if (i == j) continue;
				children.push_back(dp[v][j]);
			}
			DP now = calculate(children, ops[v]);
            bfs(bfs, g[v][i], v, now);
        }
    };
    bfs(bfs, 0, -1, DP());

	cout << ans << "\n";

	return 0;
}

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

	while (!solve()) { }

	return 0;
}
accuracy: 1
time_ms: 100
memory_kb: 37316
final_rank: 14

code_snippet: //#pragma GCC optimize("O3")
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define rep(i,n) for (ll i=0;i<(ll)n;i++)
#define rrep(i,n) for (ll i=n-1;i>=(ll)0;i--)
#define loop(i,m,n) for(ll i=m;i<=(ll)n;i++)
#define rloop(i,m,n) for(ll i=m;i>=(ll)n;i--)
#define vl vector<long long>
#define vvl vector<vector<long long>>
#define vdbg(a) rep(ii,a.size()){cout<<a[ii]<<" ";}cout<<endl;
#define vpdbg(a) rep(ii,a.size()){cout<<"{"<<a[ii].first<<","<<a[ii].second<<"} ";}cout<<endl;
#define vvdbg(a) rep(ii,a.size()){rep(jj,a[ii].size()){cout<<a[ii][jj]<<" ";}cout<<endl;}
#define setdbg(a) for(const auto & ii:a){cout<<ii<<" ";}cout<<endl;
#define inf 4000000000000000000LL
#define mod 998244353LL
//#define mod 1000000007LL
#define eps 0.000000001
random_device rnd;// 非決定的な乱数生成器
mt19937 mt(rnd());// メルセンヌ・ツイスタの32ビット版、引数は初期シード

//#include<boost/multiprecision/cpp_int.hpp>
//#define bbi boost::multiprecision::cpp_int
//#include<atcoder/lazysegtree>


//整数同士の累乗の計算をする。
ll power(ll A, ll B) {
	ll result = 1;
	for (ll i=0;i<B;i++){
		result *= A;
	}
	return result;
}

// nのk乗をmodで割った余りを計算
ll power_mod(ll n, ll k){
	long long result = 1;
	while (k > 0){
		if ((k&1) ==1)result=(result*n)%mod;
		n=n*n%mod;
		k >>= 1;
	}
	return result;
}


//受け取った2次元文字の外側に、文字pをコーティングする。
vector<string> pad(vector<string> &s,char p){
	ll h=s.size();
	ll w=s[0].size();
	vector<string> res(h+2,string(w+2,p));
	rep(i,h)rep(j,w)res[i+1][j+1]=s[i][j];
	return res;
}

// Union-Find
struct UnionFind {
	vector<int> par, siz;
	UnionFind(int n) : par(n, -1) , siz(n, 1) { }
	// 根を求める
	int root(int x) {
		if (par[x] == -1) return x;
		else return par[x] = root(par[x]);
	}
	// x と y が同じグループに属するかどうか (根が一致するかどうか)
	bool issame(int x, int y) {
		return root(x) == root(y);
	}
	// x を含むグループと y を含むグループとを併合する
	bool unite(int x, int y) {
		x = root(x), y = root(y);
		if (x == y) return false; 
		if (siz[x] < siz[y]) swap(x, y);
		par[y] = x;
		siz[x] += siz[y];
		return true;
	}
	// x を含むグループのサイズ
	int size(int x) {
		return siz[root(x)];
	}
};


//グリッド問題等用
vl dx={1,0,-1,0};
vl dy={0,1,0,-1};

vvl g;
string s;

vector<map<ll,pair<ll,ll>>> dp;

pair<ll,ll> dfs(ll node,ll before){
	if(dp[node].count(before))return dp[node][before];
	if(s[node]!='+'&&s[node]!='-'){
		dp[node][before]={s[node]-'0',s[node]-'0'};
		return dp[node][before];
	}

	pair<ll,ll> ans={-inf,inf};
	vector<pair<ll,ll>> list;
	rep(i,g[node].size()){
		if(g[node][i]==before)continue;
		list.push_back(dfs(g[node][i],node));
	}
	sort(list.begin(),list.end());

	do{
		pair<ll,ll> tmp=list[0];
		loop(i,1,list.size()-1){
			if(s[node]=='+'){
				tmp.first+=list[i].first;
				tmp.second+=list[i].second;
			}else{
				tmp.first-=list[i].second;
				tmp.second-=list[i].first;
			}
		}
		ans.first=max(ans.first,tmp.first);
		ans.second=min(ans.second,tmp.second);
	}while(next_permutation(list.begin(),list.end()));
	dp[node][before]=ans;
	return dp[node][before];
}

ll solve(){
	cin>>s;
	if(s=="-1"){return 1;}
	g=vvl(s.size());
	dp=vector<map<ll,pair<ll,ll>>>(s.size());

	vl st;
	rep(i,s.size()){
		st.push_back(i);
		if(s[i]==')'){
			ll par=st[st.size()-3];
			ll chil1=st[st.size()-2];
			ll chil2=st[st.size()-4];
			g[par].push_back(chil1);
			g[par].push_back(chil2);
			g[chil1].push_back(par);
			g[chil2].push_back(par);
			st.pop_back();
			st.pop_back();
			st.pop_back();
			st.pop_back();
			st.pop_back();
			st.push_back(par);
		}
	}
	ll par=st[st.size()-4];
	ll chil1=st[st.size()-1];
	ll chil2=st[st.size()-3];
	ll chil3=st[st.size()-5];
	g[par].push_back(chil1);
	g[par].push_back(chil2);
	g[par].push_back(chil3);
	g[chil1].push_back(par);
	g[chil2].push_back(par);
	g[chil3].push_back(par);

	ll ans=-inf;
	rep(i,s.size()){
		if(g[i].size()==3){
			ans=max(ans,dfs(i,-1).first);
		}
	}
	cout<<ans<<endl;

	return 0;
}

//メイン
int main(){
	while(solve()==0);
	return 0;
}
accuracy: 1
time_ms: 90
memory_kb: 64444
final_rank: 17

code_snippet: #include<bits/stdc++.h>
using namespace std;
typedef long long int ll;
typedef unsigned long long int ull;
#define BIG_NUM 2000000000
#define HUGE_NUM 4000000000000000000 //オーバーフローに注意
#define MOD 1000000007
#define EPS 0.000000001



#define SIZE 500005
#define MAX_DEPTH 105

struct Node{

	int value; //葉なら値あり
	char op; //■@:葉
};


int num_node;
char line[SIZE];
vector<int> V[MAX_DEPTH],children[SIZE];
int dp_min[SIZE],dp_max[SIZE],pre_min[SIZE],pre_max[SIZE];
int ans_min[SIZE],ans_max[SIZE];
Node nodes[SIZE];


int calc_E(int left,int right,int depth);
int calc_F(int left,int right,int depth);
int calc_NUM(int left,int right,int depth);


//ノード番号を返す
int calc_E(int left,int right,int depth){

	vector<int> vec;

	//深さdepthの、プラスまたは-を探す
	int L = lower_bound(V[depth].begin(),V[depth].end(),left)-V[depth].begin();
	int R = upper_bound(V[depth].begin(),V[depth].end(),right)-V[depth].begin();
	R--;

	int ind;

	if(L == V[depth].size()){ //演算子なし

		ind = calc_F(left,right,depth);

	}else{ //演算子あり

		for(int i = L; i <= R; i++){

			vec.push_back(V[depth][i]); //インデックス
		}

		if(depth == 0){ //■ルート

			ind = 0;

			nodes[0].op = line[vec[0]]; //■rootは+2個か-2個

			int a = calc_F(left,vec[0]-1,depth);
			int b = calc_F(vec[0]+1,vec[1]-1,depth);
			int c = calc_F(vec[1]+1,right,depth);

			children[0].push_back(a);
			children[0].push_back(b);
			children[0].push_back(c);

		}else{

			++num_node; //■■注意■■

			ind = num_node;
			nodes[ind].op = line[vec[0]];

			int a = calc_F(left,vec[0]-1,depth);
			int b = calc_F(vec[0]+1,right,depth);

			children[ind].push_back(a);
			children[ind].push_back(b);
		}
	}

	return ind;
}


int calc_F(int left,int right,int depth){

	if(line[left] >= '0' && line[left] <= '9'){

		return calc_NUM(left,right,depth);

	}else{ // line[left] == '('

		return calc_E(left+1,right-1,depth+1);
	}
}

int calc_NUM(int left,int right,int depth){

	++num_node;

	nodes[num_node].op = '@';
	nodes[num_node].value = line[left]-'0';

	int ret = num_node;

	return ret;
}

//■葉方向の最大値、最小値を計算
void dfs(int node){

	if(nodes[node].op == '@'){//葉

		dp_min[node] = nodes[node].value;
		dp_max[node] = nodes[node].value;

		return;
	}

	//節
	vector<int> vec;

	for(int i = 0; i < children[node].size(); i++){

		int child = children[node][i];

		dfs(child);
		vec.push_back(child);
	}

	if(nodes[node].op == '+'){

		int maxi = 0;
		int mini = 0;

		for(int i = 0; i < children[node].size(); i++){

			int child = children[node][i];

			maxi += dp_max[child]; //最大値は、各子の最大値の和
			mini += dp_min[child]; //最小値は、各子の最小値の和
		}

		dp_max[node] = maxi;
		dp_min[node] = mini;

	}else{ //nodes[node].op == '-'

		int maxi = -BIG_NUM;
		int mini = BIG_NUM;

		for(int i = 0; i < vec.size(); i++){

			int left = vec[i]; //左端のノード

			int tmp_maxi = dp_max[left];
			int tmp_mini = dp_min[left];


			for(int k = 0; k < vec.size(); k++){

				if(k == i)continue;

				tmp_maxi -= dp_min[vec[k]];
				tmp_mini -= dp_max[vec[k]];
			}

			maxi = max(maxi,tmp_maxi);
			mini = min(mini,tmp_mini);
		}

		dp_max[node] = maxi;
		dp_min[node] = mini;
	}
}

void dfs2(int node,int pre){

	if(node == 0){

		ans_min[node] = dp_min[node];
		ans_max[node] = dp_max[node];

	}else{

		if(nodes[node].op == '@')return; //葉

		/*■まずはpre_min,pre_maxを求める■*/

		if(nodes[pre].op == '+'){

			pre_min[node] = (ans_min[pre]-dp_min[node]);
			pre_max[node] = (ans_max[pre]-dp_max[node]);

		}else{ //nodes[pre].op == '-'

			vector<int> vec;

			if(pre == 0){ //■preがroot

				//■自分以外の2つの子を求める
				for(int i = 0; i < children[pre].size(); i++){

					int child = children[pre][i];
					if(child == node)continue;

					vec.push_back(child);
				}

				int a = vec[0];
				int b = vec[1];

				pre_min[node] = min(dp_min[a]-dp_max[b],dp_min[b]-dp_max[a]);
				pre_max[node] = max(dp_max[a]-dp_min[b],dp_max[b]-dp_min[a]);

			}else{  //■preがrootでない

				int tmp_min = pre_min[pre];
				int tmp_max = pre_max[pre];

				int a;
				for(int i = 0; i < children[pre].size(); i++){

					int child = children[pre][i];
					if(child != node){

						a = child;
						break;
					}
				}

				pre_min[node] = min(dp_min[a]-tmp_max,tmp_min-dp_max[a]);
				pre_max[node] = max(dp_max[a]-tmp_min,tmp_max-dp_min[a]);
			}
		}

		/*■ans_min,ans_maxを計算する■*/

		if(nodes[node].op == '+'){

			ans_max[node] = dp_max[node]+pre_max[node];
			ans_min[node] = dp_min[node]+pre_min[node];

		}else{ //nodes[node].op == '-'

			int a = children[node][0];
			int b = children[node][1];

			ans_max[node] = dp_max[a]-(dp_min[b]+pre_min[node]);
			ans_max[node] = max(ans_max[node],dp_max[b]-(dp_min[a]+pre_min[node]));
			ans_max[node] = max(ans_max[node],pre_max[node]-(dp_min[a]+dp_min[b]));


			ans_min[node] = dp_min[a]-(dp_max[b]+pre_max[node]);
			ans_min[node] = min(ans_min[node],dp_min[b]-(dp_max[a]+pre_max[node]));
			ans_min[node] = min(ans_min[node],pre_min[node]-(dp_max[a]+dp_max[b]));
		}
	}

	for(int i = 0; i < children[node].size(); i++){

		int child = children[node][i];
		dfs2(child,node);
	}
}

void func(){

	for(int i = 0; i < MAX_DEPTH; i++){

		V[i].clear();
	}
	for(int i = 0; i < SIZE; i++){

		children[i].clear();
	}

	int len;
	for(len = 0; line[len] != '\0'; len++);

	int dep = 0;

	//各深さにおける演算子の位置を前計算
	for(int i = 0; i < len; i++){
		if(line[i] == '('){

			dep++;

		}else if(line[i] == ')'){

			dep--;

		}else if(line[i] == '-' || line[i] == '+'){

			V[dep].push_back(i);
		}
	}

	num_node = 0;

	//初期状態の木構造取得
	calc_E(0,len-1,0);

	for(int i = 0; i <= num_node; i++){

		dp_min[i] = BIG_NUM;
		dp_max[i] = -BIG_NUM;

		ans_min[i] = BIG_NUM;
		ans_max[i] = -BIG_NUM;
	}

	dfs(0);
	dfs2(0,-1);

	int ans = -BIG_NUM;
	for(int i = 0; i <= num_node; i++){
		if(nodes[i].op == '@')continue;
		ans = max(ans,ans_max[i]);
	}

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

int main(){

	while(true){

		scanf("%s",line);
		if(line[0] == '-' && line[1] == '1' && line[2] == '\0')break;

		func();
	}

	return 0;
}
accuracy: 1
time_ms: 40
memory_kb: 34492
final_rank: 12

code_snippet: // AOJ #1650 Tree Transformation Puzzle
// // 2025.5.1

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

#define gc() getchar_unlocked()
#define pc(c) putchar_unlocked(c)

string Cins() {
    static char temp[500005];
    char *s = temp;
    do *s = gc();
    while (*s++ > ' ');
    *(s-1) = 0;
    string input(temp);
    return input;
}

void Cout(ll n) {
	char b[30];
	if (!n) pc('0');
	else {
		if (n < 0) pc('-'), n = -n;
		int i = 0; while (n) b[i++] = n % 10 + '0', n /= 10;
		while (i--) pc(b[i]);
	}
	pc('\n');
}

string S;
int p, n;
vector<char> c;
vector<ll> a;
vector<vector<int>> ch, g;
vector<vector<ll>> mn, mx;

int idx(int u, int v){
    for(int i = 0; i < (int)g[u].size(); ++i) if(g[u][i] == v) return i;
    return -1;
}

int pr(){
    if(isdigit(S[p])){
        int u = n++;
        c.push_back('?');
        a.push_back(S[p++] - '0');
        ch.emplace_back();
        return u;
    }
    ++p;
    int l = pr();
    char o = S[p++];
    int r = pr();
    ++p;
    int u = n++;
    c.push_back(o);
    a.push_back(0);
    ch.push_back({l, r});
    return u;
}

void dfs1(int u, int p0){
    for(int v: g[u]) if(v != p0) dfs1(v, u);
    if(p0 != -1){
        int i = idx(u, p0);
        ll mnv, mxv;
        vector<pair<ll,ll>> t;
        for(int w: g[u]) if(w != p0){
            int j = idx(w, u);
            t.emplace_back(mn[w][j], mx[w][j]);
        }
        if(c[u] == '?') mnv = mxv = a[u];
        else if(c[u] == '+'){
            mnv = t[0].first + t[1].first;
            mxv = t[0].second + t[1].second;
        } else {
            ll a0 = t[0].first, A0 = t[0].second;
            ll b0 = t[1].first, B0 = t[1].second;
            mxv = max(A0 - b0, B0 - a0);
            mnv = min(a0 - B0, b0 - A0);
        }
        mn[u][i] = mnv;
        mx[u][i] = mxv;
    }
}

void dfs2(int u, int p0){
    for(int v: g[u]) if(v != p0){
        int i = idx(u, v);
        ll mnv, mxv;
        vector<pair<ll,ll>> t;
        for(int w: g[u]) if(w != v){
            int j = idx(w, u);
            t.emplace_back(mn[w][j], mx[w][j]);
        }
        if(c[u] == '?') mnv = mxv = a[u];
        else if(c[u] == '+'){
            mnv = t[0].first + t[1].first;
            mxv = t[0].second + t[1].second;
        } else {
            ll a0 = t[0].first, A0 = t[0].second;
            ll b0 = t[1].first, B0 = t[1].second;
            mxv = max(A0 - b0, B0 - a0);
            mnv = min(a0 - B0, b0 - A0);
        }
        mn[u][i] = mnv;
        mx[u][i] = mxv;
        dfs2(v, u);
    }
}

int main(){
    while(true){
        S = Cins();
        if(S == "-1") break;

        p = 0; n = 0;
        c.clear(); a.clear(); ch.clear();

        int u1 = pr();
        char o = S[p++];
        int u2 = pr();
        ++p;
        int u3 = pr();

        int rt = n++;
        c.push_back(o);
        a.push_back(0);
        ch.push_back({u1, u2, u3});

        g.assign(n, {});
        for(int i = 0; i < n; ++i){
            for(int v: ch[i]){
                g[i].push_back(v);
                g[v].push_back(i);
            }
        }
        mn.assign(n, {});
        mx.assign(n, {});
        for(int i = 0; i < n; ++i){
            mn[i].assign(g[i].size(), 0);
            mx[i].assign(g[i].size(), 0);
        }

        dfs1(rt, -1);
        dfs2(rt, -1);

        ll ans = LLONG_MIN;
        for(int i = 0; i < n; ++i){
            if(c[i] != '?' && g[i].size() == 3){
                vector<pair<ll,ll>> t;
                for(int v: g[i]){
                    int j = idx(v, i);
                    t.emplace_back(mn[v][j], mx[v][j]);
                }
                ll cur;
                if(c[i] == '+') cur = t[0].second + t[1].second + t[2].second;
                else {
                    ll sumMin = t[0].first + t[1].first + t[2].first;
                    ll best = LLONG_MIN;
                    for(int k = 0; k < 3; ++k){
                        ll oth = sumMin - t[k].first;
                        best = max(best, t[k].second - oth);
                    }
                    cur = best;
                }
                ans = max(ans, cur);
            }
        }
        Cout(ans);
    }
    return 0;
}
accuracy: 1
time_ms: 80
memory_kb: 47272
final_rank: 15

code_snippet: #include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define all(a) a.begin(),a.end()
#define reps(i, a, n) for (int i = (a); i < (int)(n); i++)
#define rep(i, n) reps(i, 0, n)
#define rreps(i, a, n) for (int i = (a); i > (int)(n); i--)
const long long mod = 1000000007;
const long long INF = 1e18;
ll myceil(ll a, ll b) {return (a+b-1)/b;}

string s;
vector<pair<char,vector<int>>> tree(0);
vector<bool> visi(0);
vector<int> vs(0);
int now = 0;
int df2 = 0;
vector<pair<int,int>> dp(0);
vector<pair<int,int>> rdp(0);

int ans;


void al(int l, int r, int root) {
    if (r-l == 1) {
        tree[now].first = s[l];
        tree[now].second.push_back(root);
        tree[root].second.push_back(now);
        now++;
        return;
    }

    int br = 0;
    for (int i = l+1; i < r-1; i++) {
        if (s[i] == '(') br++;
        if (s[i] == ')') br--;
        if (br == 0 && (s[i] == '+' || s[i] == '-')) {
            tree[now].first = s[i];
            tree[now].second.push_back(root);
            tree[root].second.push_back(now);
            int temp = now;
            now++;
            al(l+1,i,temp);
            al(i+1,r-1,temp);
        }
    }
}

void dfs2(int x) {
    vs[x] = df2;
    df2++;


    if (tree[x].first != '+' && tree[x].first != '-') return;


    for (auto p : tree[x].second) {
        if (vs[p] < 100000000) {
            vector<pair<int,int>> temp;
            for (auto pp : tree[p].second) {
                if (pp == x) continue;
                if (vs[pp] < vs[p]) {
                    temp.push_back(rdp[p]);
                }
                else {
                    temp.push_back(dp[pp]);
                }
            }
            assert(temp.size() >= 2);
            if (tree[p].first == '+') {
                rdp[x].first = temp[0].first+temp[1].first;
                rdp[x].second = temp[0].second+temp[1].second;
            }
            else if (tree[p].first == '-') {
                rdp[x].first = max(temp[0].first-temp[1].second,temp[1].first-temp[0].second);
                rdp[x].second = min(temp[0].second-temp[1].first,temp[1].second-temp[0].first);
            }
        }
        else {
            dfs2(p);
        }
    }

    if (x == 0) {
        return;
    }


    vector<pair<int,int>> temp;
    for (auto p : tree[x].second) {
        if (vs[x] < vs[p]) {
            temp.push_back(dp[p]);
        }
        else {
            temp.push_back(rdp[x]);
        }
    }

    assert(temp.size() >= 3);
    if (tree[x].first == '+') {
        ans = max(ans,temp[0].first+temp[1].first+temp[2].first);
    }
    else if (tree[x].first == '-') {
        ans = max(ans,max(temp[0].first-temp[1].second-temp[2].second,max(temp[1].first-temp[0].second-temp[2].second,temp[2].first-temp[0].second-temp[1].second)));
    }
}


void dfs(int x) {
    visi[x] = true;
    if (tree[x].first == '+') {
        dp[x].first = 0;
        dp[x].second = 0;
        for (auto p : tree[x].second) {
            if (!visi[p]) {
                dfs(p);
                dp[x].first += dp[p].first;
                dp[x].second += dp[p].second;
            }
        }
    }
    else if (tree[x].first == '-') {
        dp[x].first = 0;
        dp[x].second = 0;
        vector<pair<int,int>> temp;
        for (auto p : tree[x].second) {
            if (!visi[p]) {
                dfs(p);
                temp.push_back({dp[p].first,dp[p].second});
            }
        }
        assert(temp.size() >= 2);

        if (temp.size() == 2) {
            dp[x].first = max(temp[0].first-temp[1].second, temp[1].first-temp[0].second);
            dp[x].second = min(temp[0].second-temp[1].first, temp[1].second-temp[0].first);
        }
        else {
            dp[x].first = max(temp[0].first-temp[1].second-temp[2].second,max(temp[1].first-temp[0].second-temp[2].second,temp[2].first-temp[0].second-temp[1].second));
            dp[x].second = min(temp[0].second-temp[1].first-temp[2].first,min(temp[1].second-temp[0].first-temp[2].first,temp[2].second-temp[0].first-temp[1].first));
        }
    }
    else {
        dp[x].first = tree[x].first - '0';
        dp[x].second = dp[x].first;
    }
}


void solve() {
    now = 0;
    int n = s.length();
    tree.resize(n);
    tree.clear();
    int br = 0;
    int root1, root2 = 0;
    rep(i,n) {
        if (s[i] == '(') br++;
        if (s[i] == ')') br--;
        if ((s[i] == '+' || s[i] == '-') && br == 0) {
            root1 = root2;
            root2 = i;
        }
    }
    tree[now].first = s[root1];
    now++;
    al(0,root1,0);
    al(root1+1,root2,0);
    al(root2+1,n,0);

    // rep(i,now) {
    //     cout << i << "   " << tree[i].first << ": ";
    //     for (auto x : tree[i].second) {
    //         cout << x << ' ';
    //     }
    //     cout << endl;
    // }


    dp.resize(now);
    visi.resize(now);
    rep(i,now+1) {
        visi[i] = false;
    }

    dfs(0);

    // rep(i,now+1) {
    //     cout << dp[i].first << ' ' << dp[i].second << endl;
    // }

    ans = dp[0].first;

    vs.resize(now);

    rep(i,now) {
        vs[i] = 1e9;
    }
    rdp.resize(now);
    df2 = 0;
    dfs2(0);

    cout << ans << endl;
    return;
}


int main() {
    cin.tie(nullptr);
    ios_base::sync_with_stdio(false);
    while (cin >> s && s != "-1") {
        solve();
    }
}
accuracy: 1
time_ms: 50
memory_kb: 26904
final_rank: 8

code_snippet: // (⁠◕⁠ᴗ⁠◕⁠✿⁠)

// #pragma GCC target("avx2")
#pragma GCC optimize("O3")
#pragma GCC optimize("unroll-loops")
#include <bits/stdc++.h>
#define rep(i, n) for (ll i = 0; i < (n); i++)
#define srep(i, s, n) for (ll i = s; i < (n); i++)
#define len(x) ((int)(x).size())
#define all(x) (x).begin(), (x).end()
using namespace std;
template<typename T> using vc = vector<T>;
template<typename T> using vv = vc<vc<T>>;
template<typename T> using vvv = vv<vc<T>>;
using vi = vc<int>;using vvi = vv<int>; using vvvi = vv<vi>;
using ll = long long;using vl = vc<ll>;using vvl = vv<ll>; using vvvl = vv<vl>;
using ld = long double; using vld = vc<ld>; using vvld = vc<vld>; using vvvld = vc<vvld>;
using uint = unsigned int;
using ull = unsigned long long;
const ld pi = acos(-1.0);
const int inf = 0x3f3f3f3f;
const ll INF = 0x3f3f3f3f3f3f3f3f;
// const ll mod = 1000000007;
const ll mod = 998244353;
inline bool inside(ll y, ll x, ll H, ll W) {return 0 <= (y) and (y) < (H) and 0 <= (x) and (x) < (W); }

#define debug(var)  do{std::cout << #var << " : \n";view(var);}while(0)
template<typename T> void view(T e){cout << e << endl;}
template<typename T> void view(const vc<T>& v){for(const auto& e : v){ cout << e << " "; } cout << endl;}
template<typename T> void view(const vv<T>& vv){ for(const auto& v : vv){ view(v); } }

int N;
vvi g;
vi num;

int id;

void f(string A, int last){ // make_tree
    int THIS = id; id++;
    if (last != -1){
        g[last].push_back(THIS);
    }
    if (len(A) == 1){
        num[THIS] = A[0] -  '0';
        return;
    }
    int p = 0;
    vc<string> child;
    char x;
    string nw = "";
    rep(i, len(A)){
        nw += A[i];
        if (A[i] == '(') p++;
        else if (A[i] == ')') p--;
        else if (p == 0 && !isdigit(A[i])){
            nw.pop_back();
            if (nw[0] == '(' && nw.back() == ')'){
                nw = nw.substr(1, len(nw) - 2);
            }
            x = A[i];
            f(nw, THIS);
            nw = "";
        }
    }
    if (nw[0] == '(' && nw.back() == ')'){
        nw = nw.substr(1, len(nw) - 2);
    }
    f(nw, THIS);
    if (x == '+') num[THIS] = -1;
    else if (x == '-') num[THIS] = -2;
    else{
        cout << "No" << endl;
    }
}

int ans;

vc<pair<int, int>> dp0, dp1;

void dfs0(int v){
    for (auto u : g[v]){
        dfs0(u);
    }
    if (v == 0){}
    else if (num[v] >= 0) dp0[v] = {num[v], num[v]};
    else if (num[v] == -1){
        dp0[v] = {0, 0};
        for (auto u : g[v]){
            dp0[v].first += dp0[u].first;
            dp0[v].second += dp0[u].second;
        }
    }else{
        dp0[v] = {0, 0};
        int ma = -inf, me = inf;
        for (auto u : g[v]){
            dp0[v].first -= dp0[u].second;
            ma = max(ma, dp0[u].first + dp0[u].second);
            dp0[v].second -= dp0[u].first;
            me = min(me, dp0[u].first + dp0[u].second);
        }
        dp0[v].first += ma;
        dp0[v].second += me;
    }
}

void dfs1(int v){
    if (v == 0){
        if (num[v] == -1){
            int nw = 0;
            for (auto u : g[v]) nw += dp0[u].first;
            ans = max(ans, nw);
        }else{
            int nw = 0, ma = -inf;
            for (auto u : g[v]){
                nw -= dp0[u].second;
                ma = max(ma, dp0[u].first + dp0[u].second);
            }
            ans = max(ans, nw + ma);
        }
        for (auto u : g[v]){
            if (num[v] == -1){
                dp1[u] = {0, 0};
                for (auto nu : g[v]) if (nu != u){
                    dp1[u].first += dp0[nu].first;
                    dp1[u].second += dp0[nu].second;
                }
            }else{
                dp1[u] = {0, 0};
                int ma = -inf, me = inf;
                for (auto nu : g[v]) if (nu != u){
                    dp1[u].first -= dp0[nu].second;
                    ma = max(ma, dp0[nu].first + dp0[nu].second);
                    dp1[u].second -= dp0[nu].first;
                    me = min(me, dp0[nu].first + dp0[nu].second);
                }
                dp1[u].first += ma;
                dp1[u].second += me;
            }
            dfs1(u);
        }
    }else if (len(g[v])){
        if (num[v] == -1){
            int nw = dp1[v].first;
            for (auto u : g[v]) nw += dp0[u].first;
            ans = max(ans, nw);
        }else{
            int nw = -dp1[v].second, ma = dp1[v].first + dp1[v].second;
            for (auto u : g[v]){
                nw -= dp0[u].second;
                ma = max(ma, dp0[u].first + dp0[u].second);
            }
            ans = max(ans, nw + ma);
        }
        for (auto u : g[v]){
            if (num[v] == -1){
                dp1[u] = dp1[v];
                for (auto nu : g[v]) if (nu != u){
                    dp1[u].first += dp0[nu].first;
                    dp1[u].second += dp0[nu].second;
                }
            }else{
                dp1[u] = {-dp1[v].second, -dp1[v].first};
                int ma = dp1[v].first + dp1[v].second, me = ma;
                for (auto nu : g[v]) if (nu != u){
                    dp1[u].first -= dp0[nu].second;
                    ma = max(ma, dp0[nu].first + dp0[nu].second);
                    dp1[u].second -= dp0[nu].first;
                    me = min(me, dp0[nu].first + dp0[nu].second);
                }
                dp1[u].first += ma;
                dp1[u].second += me;
            }
            dfs1(u);
        }
    }
}

void solve(string S){
    id = 0;
    N = 0;
    for (auto s : S) if (s != '(' && s != ')') N++;
    N--;
    g.clear();
    g.resize(N);
    num.resize(N);
    f(S, -1);

    // rep(i, N){
    //     cout << i << " : ";
    //     for (auto x : g[i]) cout << x << " ";
    //     cout << endl;
    // }
    // debug(num);
    dp0.resize(N);
    dfs0(0);
    // rep(i, N){
    //     cout << i << " " << dp0[i].first << " " << dp0[i].second << endl;
    // }
    ans = -inf;
    dp1.resize(N);
    dp1[0] = {0, 0};
    dfs1(0);
    // rep(i, N){
    //     cout << i << " " << dp1[i].first << " " << dp1[i].second << endl;
    // }
    cout << ans << "\n";
}

int main(){
    while (true){
        string S; cin >> S;
        if (S == "-1") break;
        solve(S);
    }
}
accuracy: 1
time_ms: 50
memory_kb: 17076
final_rank: 2

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
 */

vector<int> Root;
vector<vector<int>> Child;
vector<vector<int>> Ad;
vector<int> Par;
map<pair<int,int>, pair<ll,ll>> ANS;
string S;
int N;

pair<ll,ll> DFS(int X, int P) {
    if (ANS.count({X,P})) return ANS[{X,P}];
    if (Ad[X].size() == 1) {
        return ANS[{X,P}] = {(ll)(S[X]-'0'),(ll)(S[X]-'0')};
    }
    vector<pair<ll,ll>> Ret;
    rep(i,0,3) {
        if (Ad[X][i] == P) continue;
        Ret.push_back(DFS(Ad[X][i],X));
    }
    if (S[X] == '+') return ANS[{X,P}] = {Ret[0].first+Ret[1].first, Ret[0].second+Ret[1].second};
    return ANS[{X,P}] = {min(Ret[0].first-Ret[1].second,Ret[1].first-Ret[0].second),max(Ret[0].second-Ret[1].first,Ret[1].second-Ret[0].first)};
}

int MakeGraph(int L, int R, int P) {
    if (L==R) {
        Par[L] = P;
        return L;
    }
    int Dep = 0;
    int Ro = -1;
    rep(i,L,R+1) {
        if (S[i] == '(') Dep++;
        if (S[i] == ')') Dep--;
        if (Dep == 0 && (S[i] == '+' || S[i] == '-')) Ro = i;
    }
    if (Ro == -1) {
        return MakeGraph(L+1,R-1,P);
    }
    Child[Ro].push_back(MakeGraph(L,Ro-1,Ro));
    Child[Ro].push_back(MakeGraph(Ro+1,R,Ro));
    Par[Ro] = P;
    return Ro;
}

int main() {
while(1) {
    cin >> S;
    if (S == "-1") return 0;
    N = S.size();
    Child.clear();
    Child.resize(N);
    Par.clear();
    Par.resize(N,-1);
    Ad.clear();
    Ad.resize(N);
    Root.clear();
    int Dep = 0;
    rep(i,0,N) {
        if (S[i] == '(') Dep++;
        if (S[i] == ')') Dep--;
        if (Dep == 0 && (S[i] == '+' || S[i] == '-')) Root.push_back(i);
    }
    Child[Root[0]].push_back(MakeGraph(0,Root[0]-1,Root[0]));
    Child[Root[0]].push_back(MakeGraph(Root[0]+1,Root[1]-1,Root[0]));
    Child[Root[0]].push_back(MakeGraph(Root[1]+1,N-1,Root[0]));
    rep(i,0,N) {
        if (Par[i] != -1) Ad[i].push_back(Par[i]);
        for(int C : Child[i]) Ad[i].push_back(C);
    }
    ANS.clear();
    ll MAX = -inf;
    rep(i,0,N) {
        if (Ad[i].size() == 3) {
            vector<pair<ll,ll>> Ret(3);
            rep(j,0,3) {
                Ret[j] = DFS(Ad[i][j], i);
            }
            vector<int> ID(3);
            iota(ALL(ID),0);
            do {
                if (S[i] == '+') chmax(MAX, Ret[ID[0]].second + Ret[ID[1]].second + Ret[ID[2]].second);
                if (S[i] == '-') chmax(MAX, Ret[ID[0]].second - Ret[ID[1]].first - Ret[ID[2]].first);
            } while(next_permutation(ALL(ID)));
        }
    }
    cout << MAX << endl;
}
}
accuracy: 1
time_ms: 160
memory_kb: 51952
final_rank: 18

code_snippet: #include <bits/stdc++.h>
using namespace std;
using ll = long long;
constexpr ll INF = 1001001001001001001LL;

int main() {
    while(1) {
        string s; cin >> s;
        if(s == "-1") break;
        vector<vector<int>> child;
        vector<int> par;
        vector<char> op;
        vector<ll> value;
        auto num = [&](int i, int p) -> int {
            int id = child.size();
            child.push_back({});
            par.push_back(p);
            op.push_back('_');
            value.push_back(s[i]-'0');
            return id;
        };
        auto exp = [&](auto&& self, int i, int p) -> pair<int, int> {
            int id = child.size();
            child.push_back({});
            par.push_back(p);
            op.push_back('_');
            value.push_back(-1);
            for(int j = 0; j < (p==-1 ? 3 : 2); j++) {
                if(j != 0) {
                    op[id] = s[i++];
                }
                if(s[i] == '(') {
                    auto [c, e] = self(self, i+1, id);
                    child[id].push_back(c);
                    i = e+1;
                } else {
                    auto cid = num(i++, id);
                    child[id].push_back(cid);
                }
            }
            return {id, i};
        };
        auto [_, e] = exp(exp, 0, -1);
        assert(_ == 0);
        assert(e == ssize(s));
        int n = child.size();
        vector<ll> dpmax(n, -INF), dpmin(n, INF);
        stack<int> stk;
        stk.push(~0);
        stk.push(0);
        while(!stk.empty()) {
            int u = stk.top(); stk.pop();
            if(u >= 0) {
                for(int v : child[u]) {
                    if(v >= 0) {
                        stk.push(~v);
                        stk.push(v);
                    }
                }
            } else {
                u = ~u;
                int nc = ssize(child[u]);
                if(nc == 0) {
                    dpmax[u] = value[u];
                    dpmin[u] = value[u];
                    continue;
                }
                if(op[u] == '+') {
                    dpmax[u] = 0, dpmin[u] = 0;
                    for(int v : child[u]) {
                        dpmax[u] += dpmax[v];
                        dpmin[u] += dpmin[v];
                    }
                } else if(op[u] == '-') {
                    for(int c = 0; c < nc; c++) {
                        int tmpmax = 0, tmpmin = 0;
                        for(int i = 0; i < nc; i++) {
                            int v = child[u][i];
                            if(i == c) {
                                tmpmax += dpmax[v];
                                tmpmin += dpmin[v];
                            } else {
                                tmpmax -= dpmin[v];
                                tmpmin -= dpmax[v];
                            }
                        }
                        if(dpmax[u] < tmpmax) dpmax[u] = tmpmax;
                        if(dpmin[u] > tmpmin) dpmin[u] = tmpmin;
                    }
                } else assert(0);
            }
        }
        vector<ll> pardpmax(n, -INF), pardpmin(n, INF);
        stk.push(0);
        ll ans = -INF;
        while(!stk.empty()) {
            int u = stk.top(); stk.pop();
            if(value[u] != -1) continue;
            vector<ll> nearmax, nearmin;
            for(int c : child[u]) {
                nearmax.push_back(dpmax[c]);
                nearmin.push_back(dpmin[c]);
            }
            if(u != 0) {
                nearmax.push_back(pardpmax[u]);
                nearmin.push_back(pardpmin[u]);
            }
            if(op[u] == '+') {
                ll tmp = nearmax[0]+nearmax[1]+nearmax[2];
                if(ans < tmp) ans = tmp;
                for(int i = 0; i < ssize(child[u]); i++) {
                    pardpmax[child[u][i]] = nearmax[(i+1)%3]+nearmax[(i+2)%3];
                    pardpmin[child[u][i]] = nearmin[(i+1)%3]+nearmin[(i+2)%3];
                }
            } else if(op[u] == '-') {
                for(int i = 0; i < 3; i++) {
                    ll tmp = nearmax[i] - nearmin[(i+1)%3] - nearmin[(i+2)%3];
                    if(ans < tmp) ans = tmp;
                    for(int i = 0; i < ssize(child[u]); i++) {
                        pardpmax[child[u][i]] = max(nearmax[(i+1)%3]-nearmin[(i+2)%3], nearmax[(i+2)%3]-nearmin[(i+1)%3]);
                        pardpmin[child[u][i]] = min(nearmin[(i+1)%3]-nearmax[(i+2)%3], nearmin[(i+2)%3]-nearmax[(i+1)%3]);
                    }
                }
            } else assert(0);
            for(int c : child[u]) {
                stk.push(c);
            }
        }
        cout << ans << endl;
    }
}
accuracy: 1
time_ms: 30
memory_kb: 21516
final_rank: 3

code_snippet: #include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef long double ld;
typedef vector<ll> vi;
typedef vector<vi> vvi;
typedef vector<vvi> vvvi;
typedef vector<bool> vb;
typedef vector<vb> vvb;
typedef vector<vvb> vvvb;
typedef vector<vvvb> vvvvb;
typedef pair<ll,ll> pi;
typedef pair<ll,pi> ppi;
#define FOR(i,l,r) for(ll i=l;i<r;i++)
#define REP(i,n) FOR(i,0,n)
#define RFOR(i,l,r) for(ll i=r-1;i>=l;i--)
#define RREP(i,n) RFOR(i,0,n)
#define sz(A) (ll)(A.size())
#define ALL(A) A.begin(),A.end()
#define LB(A,x) (ll)(lower_bound(ALL(A),x)-A.begin())
#define UB(A,x) (ll)(upper_bound(ALL(A),x)-A.begin())
#define COU(A,x) (UB(A,x)-LB(A,x))
#define F first
#define S second
template<typename T>using min_priority_queue=priority_queue<T,vector<T>,greater<T>>;
template<typename T1,typename T2>ostream&operator<<(ostream&os,pair<T1,T2>&p){os<<p.F<<" "<<p.S;return os;}
template<typename T1,typename T2>istream&operator>>(istream&is,pair<T1,T2>&p){is>>p.F>>p.S;return is;}
template<typename T>ostream&operator<<(ostream&os,vector<T>&v){REP(i,sz(v))os<<v[i]<<(i+1!=sz(v)?" ":"");return os;}
template<typename T>istream&operator>>(istream&is,vector<T>&v){for(T&in:v)is>>in;return is;}
template<class T>bool chmax(T&a,T b){if(a<b){a=b;return 1;}return 0;}
template<class T>bool chmin(T&a,T b){if(b<a){a=b;return 1;}return 0;}
const ll mod=998244353;
template<const long long int mod=998244353>
struct modint{
  using mint=modint<mod>;
  long long int x;
  modint(long long int _x=0):x(_x%mod){if(x<0)x+=mod;}
  long long int val(){return x;}
  mint&operator=(const mint&a){x=a.x;return *this;}
  mint&operator+=(const mint&a){x+=a.x;if(x>=mod)x-=mod;return *this;}
  mint&operator-=(const mint&a){x-=a.x;if(x<0)x+=mod;return *this;}
  mint&operator*=(const mint&a){x*=a.x;x%=mod;return *this;}
  friend mint operator+(const mint&a,const mint&b){return mint(a)+=b;}
  friend mint operator-(const mint&a,const mint&b){return mint(a)-=b;}
  friend mint operator*(const mint&a,const mint&b){return mint(a)*=b;}
  mint operator-()const{return mint(0)-*this;}
  mint pow(long long int n){
    if(!n)return 1;
    mint a=1;
    mint _x=x;
    while(n){
      if(n&1)a*=_x;
      _x=_x*_x;n>>=1;
    }
    return a;
  }
  mint inv(){return pow(mod-2);}
  mint&operator/=(mint&a){return *this*=a.inv();}
  friend mint operator/(const mint&a,mint b){return mint(a)/=b;}
};
using mint=modint<998244353>;
int main(){
    while(1){
        string S;cin>>S;
        if(S=="-1")return 0;
        ll N=sz(S);
        vvi E(N);
        vi P(N);
        ll r;
        {
            //構文解析パート
            stack<ll>st;
            vi right(N);
            REP(i,N){
                if(S[i]=='(')st.emplace(i);
                if(S[i]==')')right[st.top()]=i,st.pop();
            }
            ll t=1;
            if(S[0]=='(')t=right[0]+1;
            ll u=t+2;
            if(S[t+1]=='(')u=right[t+1]+1;
            function<ll(ll,ll)>dfs=[&](ll l,ll r){
                if(S[l]=='('){l++;r--;}
                if(r-l==1){return l;}
                ll t=l+1;
                if(S[l]=='(')t=right[l]+1;
                ll a=dfs(l,t),b=dfs(t+1,r);
                P[a]=P[b]=t;
                E[t].emplace_back(a);
                E[t].emplace_back(b);
                return t;
            };
            ll a=dfs(0,t),b=dfs(t+1,u),c=dfs(u+1,N);
            P[a]=P[b]=P[c]=t;
            E[t].emplace_back(a);
            E[t].emplace_back(b);
            E[t].emplace_back(c);
            r=t;
        }
        vi DP(N,1e18),EP(N,-1e18);
        function<void(ll)>dfs=[&](ll v){
            for(auto u:E[v])dfs(u);
            if(!sz(E[v]))DP[v]=EP[v]=S[v]-'0';
            else if(sz(E[v])==2){
                if(S[v]=='+'){
                    DP[v]=DP[E[v][0]]+DP[E[v][1]];
                    EP[v]=EP[E[v][0]]+EP[E[v][1]];
                }
                else{
                    DP[v]=min(DP[E[v][0]]-EP[E[v][1]],-EP[E[v][0]]+DP[E[v][1]]);
                    EP[v]=max(EP[E[v][0]]-DP[E[v][1]],-DP[E[v][0]]+EP[E[v][1]]);
                }
            }
            else{
                if(S[v]=='+'){
                    DP[v]=DP[E[v][0]]+DP[E[v][1]]+DP[E[v][2]];
                    EP[v]=EP[E[v][0]]+EP[E[v][1]]+EP[E[v][2]];
                }
                else{
                    DP[v]=min({DP[E[v][0]]-EP[E[v][1]]-EP[E[v][2]],-EP[E[v][0]]+DP[E[v][1]]-EP[E[v][2]],-EP[E[v][0]]-EP[E[v][1]]+DP[E[v][2]]});
                    EP[v]=max({EP[E[v][0]]-DP[E[v][1]]-DP[E[v][2]],-DP[E[v][0]]+EP[E[v][1]]-DP[E[v][2]],-DP[E[v][0]]-DP[E[v][1]]+EP[E[v][2]]});
                }
            }
        };
        dfs(r);
        vi FP(N,1e18),GP(N,-1e18);
        function<void(ll)>bfs=[&](ll v){
            if(!sz(E[v]))return;
            if(S[v]=='+'){
                FP[E[v][0]]=FP[v]+DP[E[v][1]];
                GP[E[v][0]]=GP[v]+EP[E[v][1]];
                FP[E[v][1]]=FP[v]+DP[E[v][0]];
                GP[E[v][1]]=GP[v]+EP[E[v][0]];
            }
            else{
                FP[E[v][0]]=min(FP[v]-EP[E[v][1]],-GP[v]+DP[E[v][1]]);
                GP[E[v][0]]=max(GP[v]-DP[E[v][1]],-FP[v]+EP[E[v][1]]);
                FP[E[v][1]]=min(FP[v]-EP[E[v][0]],-GP[v]+DP[E[v][0]]);
                GP[E[v][1]]=max(GP[v]-DP[E[v][0]],-FP[v]+EP[E[v][0]]);
            }
            bfs(E[v][0]);
            bfs(E[v][1]);
        };
        if(S[r]=='+'){
            FP[E[r][0]]=DP[E[r][1]]+DP[E[r][2]];
            GP[E[r][0]]=EP[E[r][1]]+EP[E[r][2]];
            FP[E[r][1]]=DP[E[r][0]]+DP[E[r][2]];
            GP[E[r][1]]=EP[E[r][0]]+EP[E[r][2]];
            FP[E[r][2]]=DP[E[r][0]]+DP[E[r][1]];
            GP[E[r][2]]=EP[E[r][0]]+EP[E[r][1]];
        }
        else{
            FP[E[r][0]]=min(DP[E[r][1]]-EP[E[r][2]],-EP[E[r][1]]+DP[E[r][2]]);
            GP[E[r][0]]=max(EP[E[r][1]]-DP[E[r][2]],-DP[E[r][1]]+EP[E[r][2]]);
            FP[E[r][1]]=min(DP[E[r][0]]-EP[E[r][2]],-EP[E[r][0]]+DP[E[r][2]]);
            GP[E[r][1]]=max(EP[E[r][0]]-DP[E[r][2]],-DP[E[r][0]]+EP[E[r][2]]);
            FP[E[r][2]]=min(DP[E[r][0]]-EP[E[r][1]],-EP[E[r][0]]+DP[E[r][1]]);
            GP[E[r][2]]=max(EP[E[r][0]]-DP[E[r][1]],-DP[E[r][0]]+EP[E[r][1]]);
        }
        bfs(E[r][0]);
        bfs(E[r][1]);
        bfs(E[r][2]);
        //REP(i,N)cout<<i<<" "<<FP[i]<<" "<<GP[i]<<endl;
        ll ans=EP[r];
        REP(i,N)if(i!=r&&sz(E[i])){
            if(S[i]=='+')chmax(ans,EP[i]+GP[i]);
            if(S[i]=='-'){
                chmax(ans,GP[i]-DP[i]);
                chmax(ans,FP[i]-(DP[E[i][0]]+DP[E[i][1]]));
            }
        }
        cout<<ans<<endl;
    }
    return 0;
}
accuracy: 1
time_ms: 30
memory_kb: 31476
final_rank: 9