solved 594 div2 500pt problem