UVA - 712 S-Tree_uva

來源:互聯網
上載者:User

題目大意:滿二叉樹,節點值為 0 或 1。給出一個 n 表示該二叉樹的深度,第二行 x3,x1,x2 表示從根節點開始每一層的值,第三行表示最後一層即葉子的值。接著給出要尋找的次數 m,以下 m 行每行分別表示 x1,x2,x3 的值。有一顆小球從根節點出發,遇到 0 左走 1 右走,輸出最後到達的葉子節點的值。

解題思路:根據滿二叉樹做孩子為 2k,右孩子 2K+1 的特點解決。建立一個數組 leaf 每個下標對應二叉樹節點的編號,讀入葉子節點將每個值放入對應的編號中。讀取每一層的值計算最後到達的編號,直接從數組中讀取對應的值。

#include<iostream>#include<cstdio>#include<cstdlib>#include<cstring>#include<cmath>#include<ctype.h>using namespace std;char tmp[100];int root[10];char leaf[1000];char order[10];int cnt = 0;int main() {    int n;    char c;    while (scanf("%d\n", &n) != EOF && n) {        printf("S-Tree #%d:\n", ++cnt);        gets(tmp);        gets(leaf);        int tag = 0;        for (int i = 0; tag < n; i++)            if (tmp[i] >= '0' && tmp[i] <= '9')                root[tag++] = tmp[i]-'0';        tag = (2<<n)-1;        for (int i = strlen(leaf)-1; i >= 0; i--)            leaf[tag--] = leaf[i];        int m;        scanf("%d\n", &m);        while (m--) {            gets(order);            int sum = 1;            for (int i = 0; i < n; i++) {                if (order[root[i]-1] == '0')                    sum = sum*2;                else sum = sum * 2 + 1;            }            printf("%c", leaf[sum]);        }        printf("\n\n");    }return 0;}

聯繫我們

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