#include #include #include #include #include using namespace std; int main() { //receive input data std::vector input_list; int input_size(0); std::cin >> input_size; input_list.reserve(input_size); for (int counter(0); counter < input_size; ++counter) { int temp_input(0); std::cin >> temp_input; input_list.push_back(temp_input); } //calculate the first S(A) list (potentially 4 * 10^10 ints long) std::vector s_a; s_a.reserve(input_size*(input_size+1)/2); uint64_t j(0); int64_t max_val(0); for (uint64_t k(0); k < input_size; ++k) { for (uint64_t i(0); i < input_size-k; ++i) { j = i + k; auto start = input_list.begin() + i; auto end = input_list.end() + j + 1; max_val = *std::max_element(start, end); s_a.push_back(max_val); } } //simply calculate the SUM of the values of S(S(A)) WITHOUT storing it all in an array int64_t total_sum(0); for (uint64_t k(0); k < s_a.size(); ++k) { for (uint64_t i(0); i < s_a.size()-k; ++i) { j = i + k; auto start = s_a.begin() + i; auto end = s_a.begin() + j + 1; max_val = *std::max_element(start, end); //std::cout << max_val << " "; total_sum += max_val; } } std::cout << total_sum; return 0; }