You are given a sequence S of length at most 100 consisting of integers which represents brackets. A negative integer -x is an opening bracket of type x while x is a closing bracket of type x.
A balanced sequence of brackets is defined as usual (see the full problem statement for clarity).
We call a subsequence s of S valid if and only if s is a balanced sequence of brackets. Your task is to count the number of valid subsequences of S modulo 10^9 + 7.
QUICK EXPLANATION:
Define a dp[i][j] table where dp[i][j] := number of valid subsequence of S[i…j]. Notice that you can compute dp[i][j] if you know dp[i + 1][j] and positions of a closing bracket of type x in range from i + 1 to j if S[i] is an opening bracket of type x.
EXPLANATION:
Since input numbers can be quite large (up to 10^9) we want to compress them at the beginning in order to use them as array indices or use a hash table with O(1) lookup and insert time to do this.
Let pos[i][j][x] := list of positions of occurences of closing bracket of type x in S[i…j]
We can compute pos table in O(n^3) time using simple iteration over all 3 dimensions of it.
Let dp[i][j] := number of valid subsequences of S[i…j]
For simplicity, let’s set dp[i][j] := 1 for i > j.
Let’s assume that we have dp[i + 1][j] already computed. We want to extend it to dp[i][j]. There are two cases:
We don’t take a bracket at the i-th position, so dp[i][j] += dp[i + 1][j]
If the bracket at the i-th position is an opening bracket of type x, we can try to take it to our subsequence.
While the first case is clear, the second one requires an explanation. If there are k closing brackets of type x in S[i + 1…j] we have k different possibilities to extend shorter subsequences, i.e. dp[i][j] += dp[i + 1][b - 1] * dp[b + 1][j] where b is a single position of a closing bracket of type x in S[i + 1…j]. Since we have pos table computed, we can get values for b using a quick lookup.
Time Complexity:
The time complexity is O(N^3) because computing pos and dp tables takes this much time and any other computation step doesn’t have greater complexity.
It seems that the test cases were changed and solutions were not rejudged. My submission http://www.codechef.com/viewsolution/5495967 got 90 points, missing task #0 and if I resubmit it, it gets 100 points.
I believe such test case changes should be warned by e-mail or don’t make it default but let us choose to get an e-mail for such cases.
The editorial is marked as community wiki and thus you can edit it. In the right side (middle) of the the place where the tags are written in the end, there’s an option to edit it. See carefully… “Related problems : to be updated soon” is written
I do not understand why DP[i][j] is directly obtained from DP[i+1][j] (excluding i th bracket). I haave severe instict telling me to take DP[i][j-1] too i.e. the bracket was added on the last of the sequence i to j-1