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
#include <stdio.h>
#include <queue>

typedef long long int lli;
int main(int argc,char *argv[]) {
  int n;
  int k;
  lli sum  = 0;
  std::priority_queue<int> values;
  std::vector<int> data;
  std::priority_queue<int, std::vector<int>, std::greater<int> > sortqueue;

  scanf("%d",&n);

  k = 0;
  while(k<n) {
    int val;

    for (int i=k;i<n;i++) {
      scanf("%d",&val);
      data.push_back(val);
      sortqueue.push(val);
      //printf("reading val %d, %d, %d , %d\n",val,i,k,n);
    }
    k++;
  }


  while (!sortqueue.empty()) {
    sum += sortqueue.top();
    //printf("sorting, sortqueue.top: %d : %lld\n",sortqueue.top(),sum);
    sortqueue.pop();
  }

    sum=0;
  k=0;
  int pos = data.size();
  while(k<=n) {
    int val;
    for (int i=0;i<k;i++) {
      //printf("push to queue: %d\n",data[pos-1]);
      values.push(data[--pos]);
    }
    int removed =0;
    while (++removed < k) {
      //printf("removing from queue: %d\n",values.top());
      values.pop();
    }
    k++;
  }

  while (!values.empty()) {
    sum += values.top();
    values.pop();
  }

  printf("%lld\n",sum);
  return 0;
}

/*
1 2 3 4 5
  4 3 2 1
    3 4 5
      2 1
        5

X X 3 4 5
  4 3 X X
    3 4 5
      X X
        5


1 2 3 X 5
  X X X X
    3 4 5
      4 5
        5
*/