(* This is the key observation. An element of a sorted sequence is said to be super-increasing if it's 2 or more bigger than the sum of all the previous elements. A gap is a number that cannot be achieved but numbers greater than it can be achieved. If the sequence is super-increasing => there will be a gap If the sequence is not super-increasing => there will be a no gap We just sort all the pieces. And run through them, and see if the current piece is super-increasing (i.e. at least 2 more than s, the sum of all the previous pieces). If we hit one of the super-increasing ones, we insert a new piece of size s+1. The process continues until we run out of new pieces to add. *) let solve n m pieces = let sorted_pieces = List.sort compare pieces in let rec loop count running_total rest accum = if count = m then accum else match rest with [] -> loop (count+1) (2*running_total+1) rest ((running_total+1)::accum) | h::tail -> if h > running_total+1 then loop (count+1) (2*running_total+1) rest ((running_total+1)::accum) else loop count (running_total+h) tail accum in loop 0 0 sorted_pieces [] let main () = let read_int () = Scanf.bscanf Scanf.Scanning.stdib " %d " (fun x -> x) in let n = read_int() in let m = read_int() in let rec loop count accum = if count=n then accum else loop (count+1) ((read_int())::accum) in let pieces = loop 0 [] in let answer = List.rev (solve n m pieces) in let rec print_loop = function [] -> Printf.printf "\n" | h::tail -> Printf.printf "%d " h; print_loop tail in print_loop answer ;; main()