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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#include <iostream>
#include <algorithm>
#include <vector>
#include <set>

using namespace std;

struct range
{
   int i, j, c;
   range(int i, int j, int c) : i(i), j(j), c(c) {}

   int len() const 
   {
      return j - i + 1;
   }
};


bool sortCmp(range r1, const range & r2)
{
   return   (r1.c < r2.c) || 
            (r1.c == r2.c && r1.len() < r2.len());
}


int main(int argc, char const *argv[])
{
   ios_base::sync_with_stdio(0);
   int n;
   cin >> n;
   vector<range> ranges;
   ranges.reserve(n * (n + 1) / 2);
   for (int i = 0; i < n; ++i)
   {
      for (int j = i; j < n; ++j)
      {
         int c;
         cin >> c;
         ranges.push_back(range(i, j, c));
      }
   }

   sort(ranges.begin(), ranges.end(), sortCmp);

   vector<set<int>> known_left(n, set<int>());
   vector<set<int>> known_right(n, set<int>());
   long k = 0;
   int examined = 0;

   for (vector<range>::iterator r = ranges.begin(); examined < n && r != ranges.end(); ++r)
   {
      if (known_right[r->i].find(r->j) == known_right[r->i].end())
      {
         k += r->c;
         examined++;

         // update known_right and known_left
         set<int> rbegins; 
         set<int> rends;

         rbegins.insert(r->i);
         if (r->i > 0)
            rbegins.insert(known_left[r->i - 1].begin(), known_left[r->i - 1].end());

         rends.insert(r->j);
         if (r->j + 1 < n)
            rends.insert(known_right[r->j + 1].begin(), known_right[r->j + 1].end());


         for (set<int>::iterator rbeg = rbegins.begin(); rbeg != rbegins.end(); ++rbeg)
            known_right[*rbeg].insert(rends.begin(), rends.end());

         for (set<int>::iterator rend = rends.begin(); rend != rends.end(); ++rend)
            known_left[*rend].insert(rbegins.begin(), rbegins.end());            
      }
   }

   cout << k << endl;

   return 0;
}