Andy: AC code for UVa#11512 but not efficient.