Problem 266E partial solution, waiting for codeforces to come back up to finish it