UVA 548 Tree 建树

题意:

输入中序和后序的权值,输出哪个叶子使它到根的路径上权和最小。

思路:

输入后建树,然后dfs求最小的叶子。

  1 #include<iostream>
  2 #include<cstdio>
  3 #include<queue>
  4 #include<cstring>
  5 #include<sstream>
  6 using namespace std;
  7 
  8 int mid[10010], post[10010];
  9 int judge[1010];
 10 struct node {
 11     int index;
 12     node *left, *right;
 13     node()
 14     {
 15         left = right = NULL;
 16     }
 17 };
 18 int n;
 19 bool input(int* a)//输入函数 
 20 {
 21     string line;
 22     memset(a, 0, sizeof(a));
 23     if (!getline(cin, line))
 24         return false;
 25     stringstream ss(line);
 26     int x;
 27     n = 0;
 28     while (ss >> x)
 29         a[n++] = x;
 30     //printf("n=%d\n", n);//
 31     return n>0;
 32 }
 33 
 34 int cnt, res;
 35 node* build(node* root, int l, int r)
 36 {
 37     int i;
 38     int t = post[--cnt];
 39     for (i = l; i<r; i++)
 40     {
 41         if (t == mid[i])
 42             break;
 43     }
 44     root = new node();
 45     root->index = t;
 46     /* 注意下面是先建右边然后建左边
 47     因为后序往前走(--cnt)
 48      
 49     */
 50     if (i<r - 1) 
 51         root->right = build(root->right, i + 1, r);
 52     if (i>l)
 53         root->left = build(root->left, l, i);
 54 
 55     return root;
 56 }
 57 
 58 void preorder(node *root)
 59 {
 60     printf("%d ", root->index);
 61     if (root->left != NULL)
 62         preorder(root->left);
 63     if (root->right != NULL)
 64         preorder(root->right);
 65 }
 66 int best, best_num;
 67 void dfs(node *root, int sum)
 68 {
 69     sum += root->index;
 70     if (!root->left && !root->right)
 71     {
 72         if (best_num>sum || (sum == best_num&&root->index<best))
 73         {
 74             best = root->index;
 75             //printf("best=%d\n", best);
 76             best_num = sum;
 77         }
 78     }
 79     if (root->left != NULL)
 80         dfs(root->left, sum);
 81     if (root->right != NULL)
 82         dfs(root->right, sum);
 83 }
 84 
 85 int main()
 86 {
 87     while (input(mid))
 88     {
 89         input(post);
 90         cnt = n;
 91         //printf("cnt=%d\n", cnt);
 92         memset(judge, 0, sizeof(judge));
 93         node *root = NULL;
 94         root = build(root, 0, n);
 95         best_num = 1000000000;
 96         //preorder(root);
 97         //printf("\n");
 98         dfs(root,0);
 99         printf("%d\n",best);
100     }
101     return 0;
102 }

猜你喜欢

转载自www.cnblogs.com/fudanxi/p/10580127.html
今日推荐