Magical Indices in an array | C ++ program to find number of magical indices in the given array . ; Function to count number of magical indices . ; Array to store parent node of traversal . ; Array to determine whether current node is already counted in the cycle . ; Initialize the arrays . ; Check if current node is already traversed or not . If node is not traversed yet then parent value will be - 1. ; Traverse the graph until an already visited node is not found . ; Check parent value to ensure a cycle is present . ; Count number of nodes in the cycle . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define mp  make_pair NEW_LINE #define pb  push_back NEW_LINE #define mod  1000000007 NEW_LINE int solve ( int A [ ] , int n ) { int i , cnt = 0 , j ; int parent [ n + 1 ] ; int vis [ n + 1 ] ; memset ( parent , -1 , sizeof ( parent ) ) ; memset ( vis , 0 , sizeof ( vis ) ) ; for ( i = 0 ; i < n ; i ++ ) { j = i ; if ( parent [ j ] == -1 ) { while ( parent [ j ] == -1 ) { parent [ j ] = i ; j = ( j + A [ j ] + 1 ) % n ; } if ( parent [ j ] == i ) { while ( ! vis [ j ] ) { vis [ j ] = 1 ; cnt ++ ; j = ( j + A [ j ] + 1 ) % n ; } } } } return cnt ; } int main ( ) { int A [ ] = { 0 , 0 , 0 , 2 } ; int n = sizeof ( A ) / sizeof ( A [ 0 ] ) ; cout << solve ( A , n ) ; return 0 ; }