Solution to SPOJ BEADS problem