import java.util.*;
public class Main
{
//For every opening parenthesis '(', tells you the position of its corresponding closing parenthesis.
int[] parenMap;
int eval(String s, int start, int end) {
if (start > end)
return 0;
char c = s.charAt(start);
//Everything that follows '+' will be evaluated and returned.
if (c == '+')
return eval(s, start + 1, end);
//Evaluate what is inside parentheses, plus whatever is remaining after that.
else if (c == '(')
return eval(s, start + 1, parenMap[start] - 1) + eval(s, parenMap[start] + 1, end);
else if (c == '-') {
//The negative sign applies only to the token immediately following the sign. What comes next is evaluated normally.
if (s.charAt(start + 1) == '(')
return -eval(s, start + 2, parenMap[start + 1] - 1) + eval(s, parenMap[start + 1] + 1, end);
else {
//We have a number after the '-' sign.
int value = 0, pos = start + 1;
while (pos <= end && Character.isDigit(s.charAt(pos))) {
value = 10*value + s.charAt(pos) - '0';
++pos;
}
//Return the parsed number, and then process whatever comes after it.
return -value + eval(s, pos, end);
}
}
//Number
else {
int pos = start, value = 0;
while (pos <= end && Character.isDigit(s.charAt(pos))) {
value = 10*value + s.charAt(pos) - '0';
++pos;
}
//Return the parsed number, and then whatever comes after it.
return value + eval(s, pos, end);
}
}
public int calculate(String s) {
//Strip whitespace from input. Saves us from having to handle a few edge cases.
StringBuilder buffer = new StringBuilder(s.length());
for (int i = 0; i < s.length(); ++i) {
char c = s.charAt(i);
if (c > ' ')
buffer.append(c);
}
s = buffer.toString();
//Build the parenthesis location map.
parenMap = new int[s.length()];
ArrayDeque<Integer> stack = new ArrayDeque<Integer>();
for (int i = 0; i < s.length(); ++i) {
if (s.charAt(i) == '(')
stack.addFirst(i);
else if (s.charAt(i) == ')')
parenMap[stack.removeFirst()] = i;
}
return eval(s, 0, s.length() - 1);
}
public static void main (String[] args) {
int x = new Main().calculate("5+(1+3)-2");
System.out.println(x);
}
}