There are some problems that will seem not to be logical or that theyāll be very hard to imagine at first sight. They have this cute statement: āyou (can)/(have to) do X amount of operationsā to this array/string", like this Permutation Disturbance Practice Coding Problem - CodeChef problem you are talking about.
If you face this kind of problems, itās a good idea to give yourself a couple of minutes of writing down with pencil and paper examples of this so-called operation the problem states.
Think of counter examples, think of how you could force the operations work for you. Play with the operation so you can learn how it works and what it does. After a couple of examples that you can see with your eyes in a notebook, youāll start to spot patterns.
In this problem, you will start wondering things like:
- āIf I run each index and find a number that correlate with its index, then Iāll have to swap itā
- āBut if I swap it, would it be a risk that I bring a number to its right positionā
- āThat makes no sense, because if Iām moving the number in a permutation from its position, by definition Iām moving the disturbance oneā
And so on, so on.
Donāt be afraid to give yourself a couple of minutes of writing down and doing try and failure from what you are learning from that so-called operation.
I originally solved it on Python, but Iāll leave you a C++ equivalent I just made for this:
Feel free to ask any doubt if you donāt understand something
#include <bits/stdc++.h>
#define ll long long
using namespace std;
void solve(){
ll N;
cin >> N;
// I fill my vector with right size
vector<ll> A(N);
for(ll i=0; i<N; i++){
cin >> A[i];
}
/*
I'll try to shift the numbers to their right
There's not a strong numberical reason to do this
Or maybe it is, who cares?
I spotted this after try and failiring a couple of minutes in my notebook
*/
ll swaps = 0;
for(ll i=0; i<(N-1); i++){
ll num = i+1;
if (num == A[i]){
swap(A[i], A[i+1]);
swaps++;
}
}
// I have to be sure my last element be "distubed" too
if (A[N-1] == N){
swap(A[N-1],A[N-2]);
swaps++;
}
cout << swaps << "\n";
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int T;
cin >> T;
while(T--){
solve();
}
}
My (original) Python solution
for T in range(int(input())):
N = int(input())
A = list(map(int,input().strip().split()))
swaps = 0
for i in range(N-1):
num = i+1
if num == A[i]:
A[i], A[i+1] = A[i+1], A[i]
swaps += 1
if A[N-1] == N:
A[N-1], A[N-2] = A[N-2], A[N-1]
swaps += 1
print(swaps)