Calculate minimum cost and find minimum cost arrangement . The value c [ j ] indicates optimized cost to arrange words from word number 1 to j .
c [ 0 ] = 0 ; for ( int j = 1 ; j <= n ; j ++ ) { c [ j ] = MAX ; for ( int i = 1 ; i <= j ; i ++ ) { if ( c [ i - 1 ] != MAX && lc [ i , j ] != MAX && ( c [ i - 1 ] + lc [ i , j ] < c [ j ] ) ) { c [ j ] = c [ i - 1 ] + lc [ i , j ] ; p [ j ] = i ; } } } printSolution ( p , n ) ; }