Created
March 30, 2024 21:53
-
-
Save lsem/197b0b327536ab64c2017babfacb253c to your computer and use it in GitHub Desktop.
sorted_sum.cpp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <algorithm> | |
#include <iostream> | |
#include <string> | |
#include <utility> | |
#include <vector> | |
using namespace std; | |
// assuming array K first elements are sorted, sort so that K+1 becomes | |
// sorted. | |
void sort_n(vector<int> &a, int k) { | |
// insertion sort this. | |
int j = k; | |
while (a[j] < a[j - 1]) { | |
auto t = a[j - 1]; | |
a[j - 1] = a[j]; | |
a[j] = t; | |
j--; | |
} | |
} | |
unsigned long long sorted_sum(vector<int> a) { | |
unsigned R = 0; | |
for (int i = 0; i < a.size(); ++i) { | |
sort_n(a, i); | |
for (size_t j = 0; j < i + 1; ++j) { | |
R = (R + ((a[j] * (j + 1)) % 1000000007)) % 1000000007; | |
} | |
} | |
return R; | |
} | |
int main() { cout << sortedSum({9, 5, 8}) << "\n"; } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment