1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
|
#include <iostream>
#include <vector>
#include <algorithm>
#ifndef NDEBUG
// debugging scaffold (writing one tends to be much more productive in the long run than
// unprincipled, non-repeatable hacking using a debugger)
#include <cassert>
void show_sorted_levels( const std::vector<int>& levels )
{
std::cout << "[ " ;
for( int v : levels ) std::cout << v << ' ' ;
std::cout << "]\n" ;
// assert the invariant
assert( !levels.empty() && std::is_sorted( std::begin(levels), std::end(levels) ) ) ;
}
#else // #if defined NDEBUG
void show( const std::vector<int>& ) {} // do nothing; our code is already debugged
#endif // NDEBUG
std::vector<int>& fuse( std::vector<int>& levels ) // invariant: levels are sorted
{
show_sorted_levels(levels) ;
// try to find the first two adjacent levels which are equal (in the reverse direction)
// http://en.cppreference.com/w/cpp/algorithm/adjacent_find
// note: fusing the first two adjacent values in the reverse direction maintains the sorted order
// (because the fused value is just one greater than the original value)
const auto rev_iter = std::adjacent_find( std::rbegin(levels), std::rend(levels) ) ;
if( rev_iter == std::rend(levels) ) return levels ; // no equal levels, nothing more to fuse
// fuse the two equal levels into a single weapon
// get an iterator to the first weapon (the earlier one in the forward direction)
// http://en.cppreference.com/w/cpp/iterator/reverse_iterator/base
const auto iter = rev_iter.base() - 2 ;
++*iter ; // increment the level of that weapon
levels.erase( iter+1 ) ; // and remove the next weapon
return fuse(levels) ; // repeat the fuse operation
}
int max_fused_level( std::vector<int> levels ) // return the max level after fusing weapons
{
if( levels.empty() ) return 0 ; // sanity check
std::sort( std::begin(levels), std::end(levels) ) ; // sort the levels
return fuse(levels).back() ; // the max fused level is at the back of the sorted vector
}
int main() // minimal test driver (the first two test cases are the ones from codechef)
{
std::cout << max_fused_level( { 3, 3, 1, 4 } ) << "\n-------------\n"
<< max_fused_level( { 2, 3, 3, 3, 1, 1 } ) << "\n-------------\n"
<< max_fused_level( { 2, 3, 3, 3, 1, 1, 2, 3, 3, 3, 1, 1, 4, 4, 5, 3, 3 } ) << '\n' ;
}
|