Refactored 11512. Time Limit Exceeded on UVA