Problem:
Score : 900 points

Problem Statement

Joisino has a formula consisting of N terms: A_1 op_1 A_2 ... op_{N-1} A_N.
Here, A_i is an integer, and op_i is an binary operator either + or -.
Because Joisino loves large numbers, she wants to maximize the evaluated value of the formula by inserting an arbitrary number of pairs of parentheses (possibly zero) into the formula.
Opening parentheses can only be inserted immediately before an integer, and closing parentheses can only be inserted immediately after an integer.
It is allowed to insert any number of parentheses at a position.
Your task is to write a program to find the maximum possible evaluated value of the formula after inserting an arbitrary number of pairs of parentheses.

Constraints

1≦N≦10^5

1≦A_i≦10^9

op_i is either + or -.

Input

The input is given from Standard Input in the following format:

N
A_1 op_1 A_2 ... op_{N-1} A_N

Output

Print the maximum possible evaluated value of the formula after inserting an arbitrary number of pairs of parentheses.

Sample Input 1

3
5 - 1 - 3

Sample Output 1

7

The maximum possible value is: 5 - (1 - 3) = 7.

Sample Input 2

5
1 - 2 + 3 - 4 + 5

Sample Output 2

5

The maximum possible value is: 1 - (2 + 3 - 4) + 5 = 5.

Sample Input 3

5
1 - 20 - 13 + 14 - 5

Sample Output 3

13

The maximum possible value is: 1 - (20 - (13 + 14) - 5) = 13.

Solution in C++14 (GCC 5.4.1) (judge verdict: Accepted)


#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <climits>
#include <cfloat>
#include <cstring>
#include <map>
#include <utility>
#include <set>
#include <iostream>
#include <memory>
#include <string>
#include <vector>
#include <list>
#include <algorithm>
#include <functional>
#include <sstream>
#include <complex>
#include <stack>
#include <queue>
#include <unordered_set>
#include <unordered_map>
#include <array>
#include <cassert>
#include <bitset>
using namespace std;
using LL = long long;

int n;
LL a[114514];
bool p[114514];//true=+ false=-

const LL INF = 1e17;

int main(void)
{
	cin >> n;
	for (int i = 0; i < n; ++i)
	{
		if (i != 0)
		{
			char c;
			cin >> c;
			p[i] = (c == '+');
		}
		cin >> a[i];
	}
	p[0] = true;
	LL dp[4], ndp[4];
	dp[0] = 0;
	dp[1] = dp[2] = dp[3] = -INF;
	for (int i = 0; i < n; ++i)
	{
		fill(ndp, ndp + 4, -INF);
		for (int j = 0; j <= 2; ++j)
		{
			int jj = j + (!p[i]);
			bool neg = jj % 2;
			LL val = -114514;
			if (!p[i])
			{
				val = -a[i];
				if (!neg)val = -val;
			}
			else
			{
				val = a[i];
				if (neg)val = -val;
			}
			ndp[jj] = dp[j] + val;
		}
		//括弧を閉じる
		for (int j = 3; j >= 1; --j)
		{
			ndp[j - 1] = max(ndp[j - 1], ndp[j]);
		}
		copy(ndp, ndp + 4, dp);
	}
	cout << dp[0] << endl;
	return 0;
}