LA 3516

3516 - Exploring Pyramids

 * http://acmicpc-live-archive.uva.es/nuevoportal/data/problem.php?p=3516

Summary
Find the number of rooted trees (ignoring rotations and chosen order of traversal) with the given order of eulerian traversal of the tree whose vertexes are marked with letters.

Explanation
The problem can be solved if we define function $$F(S)$$ - the number of trees whose traversal order gives the resutling string $$S$$. For a valid $$S: S[1] = S[n]$$.

The following recurrence relation holds for the function $$F(S)$$: $$F(S) = \sum_{i = 2..n} F(S[2..i - 1]) * F(S[i..n]), iff S[1] = S[i].$$


 * 1) include 
 * 2) include 

typedef long long ll_t;

char S[400]; int P[400][400]; ll_t R[400][400];

ll_t F(int l, int r) { int i; if (l > r) return 0; if (l == r) return (S[l] == S[r]); if (P[l][r]) return R[l][r]; P[l][r] = 1, R[l][r] = 0; for (i = l + 1; i <= r; i++) if (S[i] == S[l]) R[l][r] = (R[l][r] + F(l + 1, i - 1) * F(i, r)) % 1000000000; return R[l][r]; }

int main { while (scanf ("%s", S) == 1) { memset (P, 0, sizeof(P)); printf ("%lld\n", F(0, strlen(S) - 1)); } return 0; }

Input
ABABABA ABA

Output
5 1