zoukankan      html  css  js  c++  java
  • UVa 548 -- Tree

    UVa 548 - Tree

    给你一棵树的中根序和后根序遍历,求从根到叶子组成的路径中数字和最小的那条。

    分析:DFS,树,递归。直接递归求解,用全局变量更新即可。

     1 #include<iostream>
     2 #include<cstdio>
     3 #include<sstream>
     4 #include<cstring>
     5 using namespace std;
     6 const int maxn = 10000 + 5;
     7 int in_list[maxn];///中序序列
     8 int post_list[maxn];///后序序列
     9 int ans;
    10 int ans_node;
    11 int list_len;
    12 ///按行读取输入结点序列
    13 bool read_list(int *a)
    14 {
    15     string line;
    16     if(!getline(cin,line)) return false;
    17     stringstream ss(line);
    18     int n=0;
    19     int x;
    20     while(ss >> x) a[n++] = x;
    21     list_len = n;
    22     return n > 0;
    23 }
    24 
    25 void bfs(int *in,int *post,int n,int sum)
    26 {
    27     if(n <= 0) return;
    28     if(n == 1)///到达叶子节点
    29     {
    30         ///更新解
    31         if(ans > sum+post[n-1])
    32         {
    33             ans = sum+post[n-1];ans_node = post[n-1];
    34         }
    35         ///相等的情况
    36         else if(ans == sum+post[n-1] && post[n-1]<ans_node)
    37         {
    38             ans = sum+post[n-1];ans_node = post[n-1];
    39         }
    40         return;
    41     }
    42     int root = post[n-1];
    43     int p = 0;
    44     while(in[p] != root) p++;
    45     //进入子树之前sum加上当前根节点的值
    46     sum += root;
    47     bfs(in,post,p,sum);///左子树
    48     bfs(in+p+1,post+p,n-p-1,sum);///右子树
    49 }
    50 
    51 int main()
    52 {
    53     while(read_list(in_list))
    54     {
    55         read_list(post_list);
    56         ans = 100000005;ans_node = 20000;
    57         bfs(in_list,post_list,list_len,0);
    58         cout<<ans_node<<endl;
    59     }
    60     return 0;
    61 }

  • 相关阅读:
    云服务器迁移的那些事之一
    《编译原理》(第二版)第一章的学习笔记(一)
    vs 实用扩展
    SQL多的是,你不知道的事
    Entity Framework 批量插入 提速
    oracle 回收已删除的表
    发现一个奇怪的问题!
    看到易办网的希望...
    asp.net不认为数据库字段的空值为null
    什么是伪url?
  • 原文地址:https://www.cnblogs.com/yxh-amysear/p/8449294.html
Copyright © 2011-2022 走看看