UVA 1264 - Binary Search Tree(BST+計數)

來源:互聯網
上載者:User

標籤:style   blog   http   color   os   io   for   ar   2014   

UVA 1264 - Binary Search Tree

題目連結

題意:給定一個序列,插入二叉排序樹,問有多少中序列插入後和這個樹是相同的(包括原序列)

思路:先建樹,然後dfs一遍,對於一個子樹而言,只要保證左邊和右邊順序對就可以了,所以種數為C(左右結點總數,左結點),然後根據乘法原理乘上左右子樹的情況即可

代碼:

#include <cstdio>#include <cstring>typedef long long ll;const int MAXNODE = 1111111;const int N = 21;const int MOD = 9999991;int C[N][N];struct BST {    struct Node {int l, r, val, lsz, rsz;Node() {l = 0, r = 0, val = -1; lsz = 0; rsz = 0;}    } node[MAXNODE];    int sz;    void init() {node[1] = Node();sz = 2;    }    void insert(int x, int v) {if (node[x].val == -1) {    node[x].val = v;    return;}if (v < node[x].val) {    if (!node[x].l) {node[sz] = Node();node[x].l = sz++;    }    insert(node[x].l, v);    node[x].lsz++;}else {    if (!node[x].r) {node[sz] = Node();node[x].r = sz++;    }    insert(node[x].r, v);    node[x].rsz++;}    }    int dfs(int x) {if (x == 0) return 1;return (ll)dfs(node[x].l) * dfs(node[x].r) % MOD * C[node[x].lsz + node[x].rsz][node[x].lsz] % MOD;    }    void solve() {init();int n, num;scanf("%d", &n);while (n--) {    scanf("%d", &num);    insert(1, num);}printf("%d\n", dfs(1));    }} gao;int t;void getC() {    for (int i = 0; i < N; i++) {C[i][0] = C[i][i] = 1;for (int j = 1; j < i; j++)    C[i][j] = C[i - 1][j - 1] + C[i - 1][j];    }}int main() {    getC();    scanf("%d", &t);    while (t--) {gao.solve();    }    return 0;}


UVA 1264 - Binary Search Tree(BST+計數)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.