My USACO solution here.