Sorting By Multiplication

Revision en1, by maverick_2003, 2024-04-18 19:05:31

I recently came across problem 1861D and I'm having trouble understanding the solution provided by one of the users . The solution is given below:

Link to question -> ([](http://codeforces.net/contest/1861/problem/D)

include<bits/stdc++.h>

using namespace std; int t,n,a[200005]; int main(){ cin>>t; while(t--){ cin>>n; for(int i=1;i<=n;i++){ cin>>a[i]; } int ans=INT_MAX,a2=0,a1=0; for(int i=1;i<n;i++)if(a[i]>=a[i+1])a2++; ans=min(ans,a2); for(int i=1;i<n;i++){ if(a[i]>=a[i-1])a1++; if(a[i]>=a[i+1])a2--; ans=min(ans,a2+a1); } cout<<ans<<"\n"; } return 0; }

Could you please explain how this solution works? Specifically, I'm having trouble understanding the logic behind the a1 and a2 variables and how they are used to calculate the minimum number of operations needed to sort the array in strictly ascending order.

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en2 English maverick_2003 2024-04-18 19:07:52 33
en1 English maverick_2003 2024-04-18 19:05:31 1014 Initial revision (published)