First form an array below[] where below[i] = stick no. that is below stick No. i ( i = 0 to N-1 )
for ( int i = 0; i < N; i++ ) {
int stickBelow = -1;
for ( int j = 0; j < N; j++ )
if ( i.on( j ) {
stickBelow = j;
break;
}
below[i] = stickBelow;
}
Now iterate over this array, and keep choosing the stick whose below[i] is the present stick on top.
int topStick = -1;
for ( int i = 0; i < N; i++ ) {
for ( int j = 0; j < N; j++ ) {
if ( below[j] == topStick ) {
Choose the stick j;
topStick = j;
break;
}
}
}
The above algorithm has order of complexity O(N^2).