We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
void update(long index, long value) {
while (index < tree.size()) {
tree[index] += value;
index += index & -index;
}
}
long query(long index) {
long sum = 0;
while (index > 0) {
sum += tree[index];
index -= index & -index;
}
return sum;
}
private:
vector tree;
};
long insertionSort(vector arr) {
long shifts = 0;
long maxElement = *max_element(arr.begin(), arr.end());
FenwickTree fenwickTree(maxElement);
for (long i = arr.size() - 1; i >= 0; i--) {
shifts += fenwickTree.query(arr[i] - 1);
fenwickTree.update(arr[i], 1);
}
return shifts;
}
int main()
{
ofstream fout(getenv("OUTPUT_PATH"));
string t_temp;
getline(cin, t_temp);
long t = stol(ltrim(rtrim(t_temp)));
for (long t_itr = 0; t_itr < t; t_itr++) {
string n_temp;
getline(cin, n_temp);
long n = stol(ltrim(rtrim(n_temp)));
string arr_temp_temp;
getline(cin, arr_temp_temp);
vector<string> arr_temp = split(rtrim(arr_temp_temp));
vector<long> arr(n);
for (long i = 0; i < n; i++) {
long arr_item = stol(arr_temp[i]);
arr[i] = arr_item;
}
long result = insertionSort(arr);
fout << result << "\n";
}
fout.close();
return 0;
Insertion Sort Advanced Analysis
You are viewing a single comment's thread. Return to all comments →
include
using namespace std;
string ltrim(const string &); string rtrim(const string &); vector split(const string &);
class FenwickTree { public: FenwickTree(long size) : tree(size + 1, 0) {}
private: vector tree; };
long insertionSort(vector arr) { long shifts = 0; long maxElement = *max_element(arr.begin(), arr.end()); FenwickTree fenwickTree(maxElement);
}
int main() { ofstream fout(getenv("OUTPUT_PATH"));
}
string ltrim(const string &str) { string s(str);
}
string rtrim(const string &str) { string s(str);
}
vector split(const string &str) { vector tokens;
}