bookshelf

题目:
Robby bought a new bookshelf, and he wanted to put all his N books on it. The bookshelf contains K layers,
and the heights of each layer are variable. That is, the minimum height of one layer is equal to the maximum
height of all the books in this layer. And the height of the bookshelf is the sum of all layers' heights.
Now Robby wants to make the height of his bookshelf as low as possible, but he don't want to break the order
of the books, that is, each layer must contain the consecutive books of the original book series. And each
layer must contain at least one book.

就是说有n本书,高度为h1,h2,h3,...,hn,要放进k层的书架中,并且要按照1,2,3...,n的顺序放进去,每一层至少
要放一本,书架每一层的高度是这一层书中高度的最大值,现在要求在把所有的书放进去的情况下,书
架的高度最少是多少!

DP!! 设b[i][j]为 把前i本书放进前j层的最小高度和。
则有b[i][j]=min{b[i-x][k-1]+maxh(x+1,i)}
意思是说在第j层放x本书,那么前j-1层的情况就是b[i-x][j]
maxh(x+1,i)表示序号从x+1到i中的书的高度的最大值。
按照层数j进行规划,最后的结果就是b[n][k];

mycode:
#include  < iostream >
using   namespace  std;
inline 
int  max(  int  a, int  b ) {
    
return  a > b ? a:b;
}
inline 
int  min(  int  a, int  b ) {
    
return  a < b ? a:b;
}
int  main(  ) {
    unsigned 
int  b[  101  ][  101  ];
    
int  maa[ 101   ][  101  ];
    
int  h[  101  ];
    
int  n,k;
    
while ( cin >> n >> k ) {
    
if ( n == 0 && k == 0  )  break ;
    
for int  i = 1 ;i <= n;i ++  )
        cin
>> h[ i ];
    memset( b,
255 , sizeof ( b ) );
    b[ 
1  ][  1  ] = h[  1  ];
    
for int  i = 2 ;i <= n;i ++  ) {
        b[ i ][ 
1  ] = max( b[ i - 1  ][  1  ],h[ i ] );
    }
    
for int  i = 1 ;i <= n;i ++  ){
        maa[ i ][ i ]
= h[ i ];
        
for int  j = i + 1 ;j <= n;j ++  )
        maa[ i ][ j ]
= max( maa[ i ][ j - 1  ],h[ j ] );
    }
    
for int  k1 = 2 ;k1 <= k;k1 ++  )
        
for int  n1 = k1;n1 <= n;n1 ++  )
        
for int  i = 1 ;i <= n1 - k1 + 1 ;i ++  ) {
            b[ n1 ][ k1 ]
= min(b[ n1 ][ k1 ],b[ n1 - i ][ k1 - 1  ] + maa[ n1 - i + 1  ][ n1 ] );
        }
    cout
<< b[ n ][ k ] << endl;
    }
}

你可能感兴趣的:(OO)