Find initial sequence that produces a given Array by cyclic increments upto index P | C ++ program to implement the above approach ; Function to generate and return the required initial arrangement ; Store the minimum element in the array ; Store the number of increments ; Subtract mi - 1 from every index ; Start from the last index which had been incremented ; Stores the index chosen to distribute its element ; Traverse the array cyclically and find the index whose element was distributed ; If any index has its value reduced to 0 ; Index whose element was distributed ; Store the number of increments at the starting index ; Print the original array ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findArray ( int * a , int n , int P ) { int mi = * min_element ( a , a + n ) ; int ctr = 0 ; mi = max ( 0 , mi - 1 ) ; for ( int i = 0 ; i < n ; i ++ ) { a [ i ] -= mi ; ctr += mi ; } int i = P - 1 ; int start = -1 ; while ( 1 ) { if ( a [ i ] == 0 ) { start = i ; break ; } a [ i ] -= 1 ; ctr += 1 ; i = ( i - 1 + n ) % n ; } a [ start ] = ctr ; for ( int i = 0 ; i < n ; i ++ ) { cout << a [ i ] << " , ▁ " ; } } int main ( ) { int N = 5 ; int P = 2 ; int arr [ ] = { 3 , 2 , 0 , 2 , 7 } ; findArray ( arr , N , P ) ; return 0 ; }