博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Tree UVA - 548
阅读量:4113 次
发布时间:2019-05-25

本文共 864 字,大约阅读时间需要 2 分钟。

题意:给你一棵树的中序和后序遍历,让你求一个叶节点使得叶节点到根节点的权值最小,若有多解则输出权值最小的叶子。

思路:根据树的中序和后序遍历来建树,在建树的时候可以用数组来表示数,把结点的左右子树放进两个数组里面,在求解答案的时候在递归求解。

#include 
#include
using namespace std;const int maxn=1e4+50;int in_order[maxn];int past_order[maxn];int lch[maxn];int rch[maxn];int n;bool read_line(int *a){ string s; getline(cin,s); int x; int cnt=0; stringstream ss ; ss.clear(); ss << s; while(ss>>x) { a[cnt++]=x; } n=cnt; return cnt>0;}int Build(int l1,int r1,int l2,int r2)//zhong hou{ if(l1>r1) return 0; int root=past_order[r2]; int p=l1; while(in_order[p]!=root) p++; int cnt=p-l1; lch[root]=Build(l1,p-1,l2,l2+cnt-1); rch[root]=Build(p+1,r1,l2+cnt,r2-1); return root;}int best;int sum;void dfs(int x,int cnt){ cnt+=x; if(lch[x]==0&&rch[x]==0) { if(cnt
注意stringstream的使用。

转载地址:http://afgsi.baihongyu.com/

你可能感兴趣的文章
从Executor接口设计看设计模式之最少知识法则
查看>>
OKhttp之Call接口
查看>>
application/x-www-form-urlencoded、multipart/form-data、text/plain
查看>>
关于Content-Length
查看>>
WebRequest post读取源码
查看>>
使用TcpClient可避免HttpWebRequest的常见错误
查看>>
EntityFramework 学习之一 —— 模型概述与环境搭建 .
查看>>
C# 发HTTP请求
查看>>
启动 LocalDB 和连接到 LocalDB
查看>>
Palindrome Number --回文整数
查看>>
Reverse Integer--反转整数
查看>>
Container With Most Water --装最多水的容器(重)
查看>>
Longest Common Prefix -最长公共前缀
查看>>
Letter Combinations of a Phone Number
查看>>
Single Number II --出现一次的数(重)
查看>>
Valid Parentheses --括号匹配
查看>>
Remove Element--原地移除重复元素
查看>>
Remove Duplicates from Sorted Array--从有序数组中移除重复元素
查看>>
Count and Say
查看>>
Gas Station
查看>>