A DP problem (BTCODE_F on spoj).Since constraints are small we can memoize.