UVA10312- Expression Bracketing(Catalan + 遞推)

來源:互聯網
上載者:User

標籤:style   http   color   io   os   ar   for   sp   代碼   

題目連結


題意:給出一個序列,長度為n,表示有n個x(節點),可以添加任意括弧,問說形成的串為非二叉運算式的有多少個。

思路:用總數減去二叉運算式的數量。二叉運算式可以用Catalan數求解,至於總數的話,用dp求解。dp[i][0]表示在第i個位置可以被拆分成兩個子樹,dp[i][1]表示有一個子樹。

代碼:

#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 + 遞推)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.