Solved SRM379 div2-500 at 4:50 in the morning. Submission for 351 points.