Traverse from the back of map so as to take bigger elements first
for ( auto u = count . rbegin ( ) ; u != count . rend ( ) ; u ++ ) { int j = u -> first ; int x = j * count [ j ] ; if ( d <= x ) { k += ( d + j - 1 ) / j ; break ; } k += count [ j ] ; d -= x ; } }