#P3059. [USACO12NOV] Concurrently Balanced Strings G

[USACO12NOV] Concurrently Balanced Strings G

Description

Farmer John raises a very special breed of cows known for their distinctive appearance, where each cow has a huge circular spot on its hide that, depending on the cow’s orientation, may look like a left parenthesis or a right parenthesis.

One morning, John arranges his cows into KK rows, each with NN cows (1K10,1N50,0001 \leq K \leq 10, 1 \leq N \leq 50{,}000). Since the cows face arbitrary directions, this formation can be described by KK parenthesis strings S1,...,SkS_1, ..., S_k of length NN. John is excited to notice that his herd has some “concurrently balanced” ranges, where the range i...ji...j is concurrently balanced only if in each string S1,...,SkS_1, ..., S_k the substring over that range is balanced (we will define the meaning of a single parenthesis string being balanced below). For example, if K=3K = 3, we have

  • S1=)()((())))(())S_1 = \texttt{)()((())))(())}
  • S2=()(()()()((())S_2 = \texttt{()(()()()((())}
  • S3=)))(()()))(())S_3 = \texttt{)))(()()))(())}

Then the range [3...8][3...8] is concurrently balanced because S1[3...8]=((()))S_1[3...8] = \texttt{((()))}, S2[3...8]=()()()S_2[3...8] = \texttt{()()()}, and S3[3...8]=(()())S_3[3...8] = \texttt{(()())}. The ranges [10...13][10...13] and [11...12][11...12] are also concurrently balanced.

Given KK parenthesis strings of length NN, help John count the number of pairs (i,j)(i, j) such that the range i...ji...j is concurrently balanced across all KK strings.

There are several equivalent ways to define “balanced” for a single parenthesis string. Perhaps the simplest is that the total numbers of parentheses must be equal, and for any prefix of the string, the number of left parentheses must be at least as many as the number of right parentheses. For example, the following strings are balanced:

  • ()\texttt{()}
  • (())\texttt{(())}
  • ()(()())\texttt{()(()())}

And these strings are not balanced:

  • )(\texttt{)(}
  • ())(\texttt{())(}
  • ((())))\texttt{((())))}

Given KK sequences of length NN consisting of parentheses, how many intervals are there such that the corresponding substrings are balanced in all KK sequences?

Input Format

The first line contains two integers KK and NN.

The second through the (K+1)(K+1)-th lines: each line contains a parenthesis string of length NN.

Output Format

The first line contains a single integer, the number of concurrently balanced ranges.

3 14 
)()((())))(()) 
()(()()()((()) 
)))(()()))(()) 

3 

Hint

Translated by ChatGPT 5