This Python submission is believed to be correct. It runs too slowly when run by python, but may be acceptable when run on pypy.