#include #include #include #include #include #include #include int solve1(int A_size, int* A); int partition(int arr[], int l, int r); // This function returns k'th smallest element in arr[l..r] using // QuickSort based method. ASSUMPTION: ALL ELEMENTS IN ARR[] ARE DISTINCT int kthSmallest(int arr[], int l, int r, int k) { // If k is smaller than number of elements in array if (k > 0 && k <= r - l + 1) { // Partition the array around last element and get // position of pivot element in sorted array int pos = partition(arr, l, r); // If position is same as k if (pos-l == k-1) return arr[pos]; if (pos-l > k-1) // If position is more, recur for left subarray return kthSmallest(arr, l, pos-1, k); // Else recur for right subarray return kthSmallest(arr, pos+1, r, k-pos+l-1); } // If k is more than number of elements in array return INT_MAX; } void swap(int *a, int *b) { int temp = *a; *a = *b; *b = temp; } // Standard partition process of QuickSort(). It considers the last // element as pivot and moves all smaller element to left of it // and greater elements to right int partition(int arr[], int l, int r) { int x = arr[r], i = l; for (int j = l; j <= r - 1; j++) { if (arr[j] >= x) { swap(&arr[i], &arr[j]); i++; } } swap(&arr[i], &arr[r]); return i; } int solve(int A_size, int* A) { int *b, count = -1, k, i, j, sum = 0; b = (int *)malloc(sizeof(int)*1000000); for(k = 0; k <= A_size - 1; k++){ for(i = 0; i <= A_size - k - 1; i++){ j = i + k; b[++count] = kthSmallest(A, i, j, 1); } } sum = solve1(count+1, b); return sum; // Return the sum of S(S(A)) modulo 10^9+7. } int solve1(int A_size, int* A) { int *c, count = -1, k, i, j, sum = 0; for(i = 0; i < A_size; i++) c = (int *)malloc(sizeof(int)*1000000); for(k = 0; k <= A_size - 1; k++){ for(i = 0; i <= A_size - k - 1; i++){ j = i + k; c[++count] = kthSmallest(A, i, j, 1); } } for(i = 0; i < count+1; i++) sum += c[i]; return sum; // Return the sum of S(S(A)) modulo 10^9+7. } int main() { int n; scanf("%i", &n); int *A = malloc(sizeof(int) * n); for (int A_i = 0; A_i < n; A_i++) { scanf("%i",&A[A_i]); } int result = solve(n, A); printf("%d\n", result); return 0; }