1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#include <iostream>

using namespace std;

bool isGood(int *cities, int start, int end)
{
	long long sum = 0;
	for (int i=start;i<end;++i)
	{
		sum+=cities[i];
		if (i==end-1)
		{
			if (sum < 0)
				return false;
			sum = 0;
		}
	}
	return true;
}

void printSplits(int **splits, int row, int n)
{
	for (int i=0;i<n-row;++i)
		cout << splits[row][i] << " ";
	cout << endl;
}


int main()
{
	int n;
	cin >> n;
	int *cities = new int[n];
	int **splits = new int*[n];
	for (int i=0;i<n;++i)
	{
		splits[i] = new int[n-i];
	}
	long long sum = 0;
	for (int i = 0;i<n;i++)
	{
		cin >> cities[i];
		sum += cities[i];
		splits[0][i] = (cities[i]>=0?0:-1);
	}
	for (int i=1;i<n;++i)
	{
		for (int j=0;j<n-i;++j)
		{
			if (!isGood(cities,j,j+i+1))
			{
				splits[i][j]=-1;
				continue;
			}
			splits[i][j]=i;
			for (int k=0;k<i;++k)
			{
				if (splits[k][j] == -1 || splits[i-k-1][j+k+1] == -1) continue;
				if (splits[k][j]+splits[i-k-1][j+k+1] < splits[i][j]) splits[i][j]=splits[k][j]+splits[i-k-1][j+k+1];
			}
		}
	}
	cout << splits[n-1][0] << endl;
	delete[] cities;
	for (int i=0;i<n;++i) delete[] splits[i];
	delete[] splits;
	return 0;
}