Introduced: catlan number.
Catalan number, also known as catalan number, is a series that often appears in various counting problems in composite mathematics.
-- Baidu encyclopedia
I. calculation formula.
Let H (0) = 1, H (1) = 1, and the catalan number satisfy the recursive formula:
H (n) = H (0) * H (n-1) + H (1) * H (n-2) +... + H (n-1) * H (0) (N> = 2)Example: H (3) = H (0) * H (2) + H (1) * H (1) + H (2) * H (0) = 1*2 + 1*1 + 2*1 = 5 2: code implementation.
# Include <bits/stdc ++. h> int N, F [30]; int main () {scanf ("% d", & N); F [0] = 1, F [1] = 1; for (INT I = 2; I <= N; I ++) for (Int J = 0; j <I; j ++) f [I] + = f [J] * f [i-j-1]; // catlan number printf ("% d", F [N]); Return 0 ;}
Recursive algorithms are used here.
It can also be implemented using recursion:
# Include <bits/stdc ++. h> using namespace STD; int H (int n)
{If (n = 0 | n = 1) return 1; return H (n-1) * (4 * N-2)/(n + 1 ); // formula} int main () {int N; CIN> N; cout <H (n); Return 0 ;}
3. Application.
· Description
Luogu p1044 stack [original question link]
· Resolution
The description of this question is very simple. N numbers are added to the stack sequentially, And the stack can be randomly output. There are several possibilities.
DFS can be implemented, but when you think carefully, you will find a simpler method.
Let's create array F.F [I] indicates the full possibility of I entry and exit.
Then f [0] = 1, F [1] = 1; (there is no other possibility of 0 or 1 .)
If X is the last of the current output stack sequence, X has n values.
Since X is the last outbound stack, you can divide the number of outbound stacks into two parts.
- Smaller than X
- Larger than X
A number smaller than X has a X-1, so all of these numbers may be f [x-1]
There are n-X numbers greater than X, so the full output stack of these numbers may be f [n-x]
These two partsMutual Influence, SoAll possible values of X are f [x-1] * f [n-X].
In addition, X has n values, so:
Ans = f [0] * f [n-1] + F [1] * f [N-2] +... + F [n-1] * f [0];
Obviously --Catlands!
The data scope of the question is very small, so you can paste the template directly.
Iv. Summary. So, let's do it first.
The Catalan number has the following usage:
- Brackets matrix concatenation:P = A1 × a2 × A3 × ...... ×An: According to the multiplication combination law, without changing its order, we only use parentheses to represent the product of pairs. How many methods are there to enclose? (H (n)
- The given nodes form a binary search tree:How many different binary search trees can a given n nodes constitute? (Can constitute H (N) (the subscript of this formula starts from H (0) = 1)
N correct matching numbers of parentheses:Given n pairs of parentheses, evaluate the number of strings correctly matched by parentheses. (H (n)
· Classic exercise
P1722 matrix II [original question link]
Introduction to "catlan number"