SORTPREF - Editorial

PROBLEM LINK:

Practice
Contest: Division 1
Contest: Division 2
Contest: Division 3
Contest: Division 4

Author: raysh07
Tester: sushil2006
Editorialist: raysh07

DIFFICULTY:

Simple

PREREQUISITES:

None

PROBLEM:

You have a permutation A. You can sort A[1, i] for a cost of A_i. What is the minimum total cost needed to sort the array?

EXPLANATION:

First of all, let’s find the largest index p such that A_p \ne p. (If no such index exists, the array is already sorted, so the answer is 0).

Now, if we only choose i < p, then we are never able to sort the array because A_p is not fixed. Hence, we must use i \ge p at some point.

Further, if we use any index i \ge p, then it sorts the entire array because the suffix was already sorted. Hence, we only need one operation which we should perform with any index i \ge p.

To minimize the cost, we choose the minimum A_i among all i \ge p.

Actually, it can be proven that this minima is obtained at p itself, hence the answer is A_p (A_i = i for all i > p, and A_p < p because permutation).

TIME COMPLEXITY:

\mathcal{O}(N) per testcase.

CODE:

Editorialist's Code (C++)
#include <bits/stdc++.h>
using namespace std;
#define int long long
#define INF (int)1e18

mt19937_64 RNG(chrono::steady_clock::now().time_since_epoch().count());

void Solve() 
{
    int n; cin >> n;
    
    vector <int> a(n);
    for (auto &x : a) cin >> x;
    
    int p = n - 1;
    while (p >= 0 && a[p] == p + 1){
        p--;
    }
    
    if (p < 0){
        cout << 0 << "\n";
        return;
    }
    
    cout << a[p] << "\n";
}

int32_t main() 
{
    auto begin = std::chrono::high_resolution_clock::now();
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    int t = 1;
    // freopen("in",  "r", stdin);
    // freopen("out", "w", stdout);
    
    cin >> t;
    for(int i = 1; i <= t; i++) 
    {
        //cout << "Case #" << i << ": ";
        Solve();
    }
    auto end = std::chrono::high_resolution_clock::now();
    auto elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(end - begin);
    cerr << "Time measured: " << elapsed.count() * 1e-9 << " seconds.\n"; 
    return 0;
}```