1. 程式人生 > >和諧的奶牛Balanced Cow Breeds

和諧的奶牛Balanced Cow Breeds

題目

農夫約翰的奶牛們排成了一條直線,每隻奶牛都有一個識別符號,這個識別符號是左括號或者右括號。約翰希望將這個奶牛序列分成兩個子序列,並且不改變序列中原來的字元順序。同時,要求這兩個子序列都是平衡序列。 平衡序列是這麼定義的:序列中左括號和右括號的個數是一樣的,同時這個序列的所有字首串中左括號的個數不少於右括號的個數。

例如圖1都是平衡序列。 () (()) ()(()()) 圖2都不是平衡序列。 )( ())( ((()))) 請你幫助約翰計算將原來的奶牛序列分成兩個平衡子序列的方案數。

輸入

只有一個奶牛的序列,都是由左括號和右括號組成的。

輸出

總的方案數。

樣例輸入

(())

樣例輸出

6

資料範圍限制

序列的長度是1110001000

題解

We’ll call the two breeds A and B for convenience. Let the input string S=s1s2...snS = s_1s_2...s_n. 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}) be the number of ways to assign s

i...sns_i...s_n to breeds such that the resulting two parentheses-strings are balanced, given that we have AopenA_{open} unmatched left-parenthesis of type A and B_open unmatched left-parentheses of type B. If 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)
, since we can assign the parenthesis to breed A or breed B. If S[i]==)S[i]==')', then we can assign the parenthesis to breed A as long as Aopen>0A_{open} > 0, and to B as long as Bopen>0B_{open} > 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) = 1.

We have 0<=i<=n,0<=Aopen<=n,0<=Bopen<=n0 <= i <= n, 0 <= A_{open} <= n, 0 <= B_{open} <= n, so the number of states is O(n3)O(n^3), and there is O(1)O(1) non-recursive overhead for each state, so this leads to an O(n3)O(n^3)solution.

Unfortunately, O(n3)O(n^3) isn’t fast enough with n=1,000n=1,000. We can do better by noticing that BopenB_{open} is uniquely determined by i and Aopen(becauseAopen+BopenA_{open} (because A_{open} + B_{open} sums to the number of unmatched left-parentheses in s1...si1)s_1...s_{i-1}). So it suffices to keep track of (i,Aopen)(i, A_{open}), which gives O(n2)statesandanO(n2)O(n^2) states \ and\ an O(n^2) 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;
}