Solution for a problem statement of codeforces
The code below is my implementation for the problem Permutation Chains of CodeForces platform.
I think it handles all the corner cases but haven't tested it.
The battery is little low, so I can't describe the whole code although have left few comments for perusal.
Happy Tinkering! :)
#include<iostream>
#include<vector>
using namespace std;
//Function to print an array having int variables
void int_vect(vector<int> arr){
int arr_size=arr.size();
for(int i=0;i<arr_size;i++){
cout<<arr[i]<<" ";
}cout<<endl;
}
//Function to find the fixedness of the permutation
//OPTIONAL Function
void find_fixedness(vector<int> arr){
int arr_size=arr.size();
int fixedness=0;
for(int i=0;i<arr_size;i++){
if(arr[i]==i+1){
fixedness+=1;
}
}
cout<<"The fixedness is-->"<<fixedness<<endl;
}
int main() {
int n;
//Prompting the user for the number of testCases
cout<<"Enter the number of Test Cases ";
//Taking the testCases as input
int t;
cin>>t;
//Using a while loop for the testCases
while(t>0){
//Getting the value of n
cout<<"Enter the value of n ";
cin>>n;
vector<int> arr(n);
/*Initialising each member of the array with the
*respective values
*/
for(int i=0;i<n;i++){
arr[i]=i+1;
}
cout<<"The array is:-\t";
int_vect(arr);
find_fixedness(arr);
/****The main part of the problem*****/
int itr=n-1;
while(itr>0){
//Variable for swapping the elements
int temp;
temp=arr[itr];
arr[itr]=arr[itr-1];
arr[itr-1]=temp;
/* int_vect function for the display of
* the vector array
*/
int_vect(arr);
find_fixedness(arr);
/* Decreasing the itr by 2 for the first
* time and
* then decresing it by 1 for every iteration
*/
if(itr==n){
itr-=2;
}else{
itr-=1;
}
}
//Decreasing t after every testCase
t--;
}
return 0;
}
Comments
Post a Comment