Insertion Sort Advanced Analysis

  • + 0 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) {}

    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;
    

    }

    string ltrim(const string &str) { string s(str);

    s.erase(
        s.begin(),
        find_if(s.begin(), s.end(), not1(ptr_fun<int, int>(isspace)))
    );
    
    return s;
    

    }

    string rtrim(const string &str) { string s(str);

    s.erase(
        find_if(s.rbegin(), s.rend(), not1(ptr_fun<int, int>(isspace))).base(),
        s.end()
    );
    
    return s;
    

    }

    vector split(const string &str) { vector tokens;

    string::size_type start = 0;
    string::size_type end = 0;
    
    while ((end = str.find(" ", start)) != string::npos) {
        tokens.push_back(str.substr(start, end - start));
    
        start = end + 1;
    }
    
    tokens.push_back(str.substr(start));
    
    return tokens;
    

    }