improved greedy.cpp to run faster