题目
农夫约翰的奶牛们排成了一条直线,每只奶牛都有一个标识符,这个标识符是左括号或者右括号。约翰希望将这个奶牛序列分成两个子序列,并且不改变序列中原来的字符顺序。同时,要求这两个子序列都是平衡序列。
平衡序列是这么定义的:序列中左括号和右括号的个数是一样的,同时这个序列的所有前缀串中左括号的个数不少于右括号的个数。
例如图1都是平衡序列。
()
(())
()(()())
图2都不是平衡序列。
)(
())(
((())))
请你帮助约翰计算将原来的奶牛序列分成两个平衡子序列的方案数。
输入
只有一个奶牛的序列,都是由左括号和右括号组成的。
输出
总的方案数。
样例输入
(())
样例输出
6
数据范围限制
序列的长度是111到100010001000。
题解
We’ll call the two breeds A and B for convenience. Let the input string S=s1s2...snS = s_1s_2...s_nS=s1s2...sn. We will give a dynamic programming algorithm working backwards from the end of the string.
Let f(i,Aopen,Bopen)f(i,A_{open}, B_{open})f(i,Aopen,Bopen) be the number of ways to assign si...sns_i...s_nsi...sn to breeds such that the resulting two parentheses-strings are balanced, given that we have AopenA_{open}Aopen unmatched left-parenthesis of type A and B_open unmatched left-parentheses of type B. If S[i]==′(′S[i]=='('S[i]==′(′, then f(i,Aopen,Bopen)=f(i+1,Aopen+1,Bopen)+f(i+1,Aopen,Bopen+1)f(i,A_{open}, B_{open}) = f(i+1, A_{open}+1, B_{open}) + f(i+1, A_{open}, B_{open} + 1)f(i,Aopen,Bopen)=f(i+1,Aopen+1,Bopen)+f(i+1,Aopen,Bopen+1), since we can assign the parenthesis to breed A or breed B. If S[i]==′)′S[i]==')'S[i]==′)′, then we can assign the parenthesis to breed A as long as Aopen>0A_{open} > 0Aopen>0, and to B as long as Bopen>0B_{open} > 0Bopen>0.
The base case is i=n, in which case we processed the whole string without violating any invariants. As the total number of ')'s equals to the total number of ′(′'('′(′s, we wil end up with two balanced strings of parentheses. Therefore we can start with so f(n,0,0)=1f(n, 0, 0) = 1f(n,0,0)=1.
We have 0<=i<=n,0<=Aopen<=n,0<=Bopen<=n0 <= i <= n, 0 <= A_{open} <= n, 0 <= B_{open} <= n0<=i<=n,0<=Aopen<=n,0<=Bopen<=n, so the number of states is O(n3)O(n^3)O(n3), and there is O(1)O(1)O(1) non-recursive overhead for each state, so this leads to an O(n3)O(n^3)O(n3)solution.
Unfortunately, O(n3)O(n^3)O(n3) isn’t fast enough with n=1,000n=1,000n=1,000. We can do better by noticing that BopenB_{open}Bopen is uniquely determined by i and Aopen(becauseAopen+BopenA_{open} (because A_{open} + B_{open}Aopen(becauseAopen+Bopen sums to the number of unmatched left-parentheses in s1...si−1)s_1...s_{i-1})s1...si−1). So it suffices to keep track of (i,Aopen)(i, A_{open})(i,Aopen), which gives O(n2)states and anO(n2)O(n^2) states \ and\ an O(n^2)O(n2)states and anO(n2) solution. This is fast enough.
Code
#include <iostream>
#include <vector>
#include <cstring>
#include <cstdio>
using namespace std;
#define MOD 2012
#define MAXN 1010
int a[MAXN];
int main()
{
freopen("bbreeds.in","r",stdin);
freopen("bbreeds.out","w",stdout);
int l = a[1] = 1;
for(int ch = cin.get();l > 0 && ch == '(' || ch == ')';ch = cin.get())
{
int dir = ch == '(' ? 1 : -1;
l += dir;
for(int j = dir < 0 ? 1 : l;1 <= j && j <= l; j -= dir)
{
a[j] += a[j - dir];
if(a[j] >= MOD)
a[j] -= MOD;
}
a[l + 1] = 0;
}
cout << (l == 1 ? a[1] : 0) << endl;
}