Uva10312-expression bracketing (Catalan + recursion)

Source: Internet
Author: User

Question Link


Question: Give a sequence with a length of N, which indicates that there are N x (nodes). You can add any parentheses and ask how many strings are in a non-Binary Expression.

Idea: subtract the number of binary expressions from the total number. The binary expression can be solved using the catalan number. For the total number, use the DP. DP [I] [0] indicates that it can be split into two Subtrees at the position I. DP [I] [1] indicates that there is a subtree.

Code:

#include <iostream>#include <cstdio>#include <cstring>#include <algorithm>using namespace std;typedef long long ll;const int MAXN = 30;ll Catalan[MAXN], dp[MAXN][2];int n;void init() {    memset(Catalan, 0, sizeof(Catalan));    Catalan[1] = Catalan[2] = 1;    for (int i = 3; i < MAXN; i++)        Catalan[i] = Catalan[i - 1] * (4 * i - 6) / i; }ll dfs(int n, int m) {    ll& ans = dp[n][m];    if (ans != 0)        return ans;    if (n <= 1)        return 1;    ans = 0;    for (int i = 1; i < n + m; i++)        ans += dfs(i, 1) * dfs(n - i, 0);    return ans;}int main() {    init();    while (scanf("%d", &n) != EOF) {        memset(dp, 0, sizeof(dp));         printf("%lld\n", dfs(n, 0) - Catalan[n]);    }    return 0;}


Uva10312-expression bracketing (Catalan + recursion)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.