UVa 10328 - Coin Toss

Summary
How many distinct sequences of coin tosses of length n there are so that it contains at least k consecutive heads?

Explanation
It might not be easy to directly answer the question. But it is easy to answer how many sequences there are with no k consecutive heads. To do that, one can simply run a DP solution, with the states (toss, consecutive heads until now). dp(i, c) = 1                          if i == n,             = dp(i+1, 0)                  if c + 1 < k,             = dp(i+1, 0) + dp(i+1, c+1)   otherwise. The answer to the problem is the total number of sequences (2^n) subtracted dp(0, 0).

Another approach is to use bottom up dp where we need only one state i.e. number of toss to compute value of at least k consecutive heads. The formula I derived is dp(n+1) = 2*dp(n)+(2^(n-k)-dp(n-k)). Think if the n+1th toss gives T. Answer would be dp(n). Problem arises when n+1th toss gives H. It will be equal to dp(n) + some number(let x) as dp(n) is a subcase of it. Here x= number of states where there is k-1 consecutive heads which ends in nth position and no consecutive heads longer than k-1. So, our n-kth tern must come tail and after that we get k-1 consecutive heads and from n-k-1 to 1 there may be any combination. It can be done in 2^(n-k) ways. But here a problem arises. By taking random heads and tails we have taken some consecutive heads greater than k-1. So, no. of possible combinations where no longer consecutive heads than k-1 are present will be 2^(n-k)-dp(n-k). That's why answer comes as dp(n+1) = 2*dp(n) + (2^(n - k) - dp(n - k)).

Optimizations
A small optimization is to preprocess all powers of two less than 101.

Input
4 1 4 2 4 3 4 4 6 2

Output
15 8 3 1 4