SPOJ: ARMY (Cheated on this one. Accidentally saw the algo in the comments section.)