Oh, what a lovely problem. Such a simple problem statement, and such a lovely structure of possible solutions! Let's start with the obvious step: taking the input and sorting it according to the frozen standings. Now we can, for each coder c, precompute two values: L[c], the leftmost coder that can be worse or equal than c (if c solves an additional problem), and R[c], the rightmost coder that can be better or equal. (In both cases, the "or equal" phrase is there so that we'll have L[c]==c if there is nobody to beat, and c==R[c] if there is nobody who can overtake us.) All L and R values can be computed in linear time -- just note that they never decrease. Also, note that each of the two intervals is contiguous: c can overtake anyone between c and L[c], and be overtaken by anyone between c and R[c]. Now, there are 2^N ways how to choose which coders solved +1 problem and which ones did not. We can view each of those ways as a bit string of length N. Of course, sometimes different choices produce the same ranking. (For example, 00...00 and 11...11 always produce the same ranking.) For each possible final ranking, we want to find and count the lexicographically smallest bit string that produces it. In other words, we are interested in a bit string iff there is no smaller string that produces the same ranking. How do those strings look like? There is a fairly obvious necessary condition: there cannot be any c such that the string has 1s at positions L[c] through c, and 0s at positions c+1 through R[c]. Why? Because if we flipped the 1 at position c to a 0, we would get the same ranking. It is far less obvious that the above set of conditions is also sufficient. This can be proved by considering a sequence backwards and proving that you cannot change anything. This observation can now give us an O(n^3) DP: for each prefix length n and each i,j we will count valid sequences of 0s and 1s that end in 1^i 0^j. ("valid" == "they do not contain any of the forbidden patterns) This DP can then be optimized down to O(n log n), and there is also a more clever implementation of the counting that runs in O(n). I'll omit the details for now.