九度-1044-Pre-Post[分治和组合数] | Acm之家


九度-1044-Pre-Post[分治和组合数] | Acm之家
      We are all familiar with pre-order, in-order and post-order traversals of binary trees. A common problem in data structure classes is to find the pre-order traversal of a binary tree when given the in-order and post-order traversals. Alternatively, you can find the post-order traversal when given the in-order and pre-order. However, in general you cannot determine the in-order traversal of a tree when given its pre-order and post-order traversals. Consider the four binary trees below:
1044_Pre_Post
All of these trees have the same pre-order and post-order traversals. This phenomenon is not restricted to binary trees, but holds for general m-ary trees as well.
输入:
        Input will consist of multiple problem instances. Each instance will consist of a line of the form
m s1 s2
indicating that the trees are m-ary trees, s1 is the pre-order traversal and s2 is the post-order traversal.All traversal strings will consist of lowercase alphabetic characters. For all input instances, 1 <= m <= 20 and the length of s1 and s2 will be between 1 and 26 inclusive. If the length of s1 is k (which is the same as the length of s2, of course), the first k letters of the alphabet will be used in the strings. An input line of 0 will terminate the input.
输出:
        For each problem instance, you should output one line containing the number of possible trees which would result in the pre-order and post-order traversals for the instance. All output values will be within the range of a 32-bit signed integer. For each problem instance, you are guaranteed that there is at least one tree with the given pre-order and post-order traversals.
样例输入:
2 abc cba  2 abc bca  10 abc bca  13 abejkcfghid jkebfghicda
样例输出:
4  1  45  207352860

题目大意:对于n叉树,给出先序遍历和后续遍历,求可能的个数。
递归和组合数学。
例如:
10 abc bca
根节点为a是确定的,接下来是 bc bc
可知b,c在同一级别,有C(10,2)=45 (10个位置中取两个)
2 abc cba
同样根节点为a,然后是 bc cb
b,c在两层 C(2,1) * C(2,1)=4
对于这个就有些复杂了,
13 abejkcfghid jkebfghicda
第一步拆分为 三部分 (bejk, cfghi, d) * C(13,3)
http://blog.csdn.net/u013027996/article/details/21638269
        例一:已知二叉树的先序遍历为:abc,后序遍历为:cba,求满足条件的二叉树的个数。
        分析:首先容易得出二叉树的根结点一定是a,再由剩下的先序遍历结点序列bc(第一个结点为b)和后序遍历结点序列cb(最后一个结点为b),可知结点bc共同组成根结点a的一个子树,且其中结点b一定是该子树的根结点。这个子树可以是根结点a的左子树,也可以是右子树。如下图所示:
        
        所以,满足条件的二叉树的个数sum至少为2(sum=2)。又因为对于结点bc来说,c不管是其左结点还是右结点,都满足先序和后序遍历的要求。因此满足条件的二叉树的个数sum=sum*2=2*2=4。其形状如下图所示:
        
        例二:已知10叉树的先序遍历为:abc,后序遍历为:bca,求满足条件的10叉树的个数。
        分析:首先容易得出二叉树的根结点一定是a,再由剩下的先序遍历结点序列bc和后序遍历结点序列bc完全相同,可知结点bc不能组成根结点a的一个子树,结点b和c只能是根结点a的叶结点,并且结点b一定处于结点c的左边。因为是10叉树,所以根结点a可以有10个子结点,设编号为1~10,则结点b和c的编号可以是:(1,2)、(1,3)、(1,4)、(1,5)、(1,6)、(1,7)、(1,8)、(1,9)、(1,10)、(2,3)、(2,4)、……,由组合数知识可知符合条件的共有种。
        例三:已知13叉树的先序遍历为:abejkcfghid,后序遍历为:jkebfghicda,求满足条件的13叉树的个数。
        分析:首先容易得出二叉树的根结点一定是a,再由剩下的先序遍历结点序列bejkcfghid(第一个结点为b)和后序遍历结点序列jkebfghicd(最后一个结点为d),其首尾结点不一样,可知结点集合{bejkcfghid}不可能构成根结点的一个子树,也就是说,根结点a的子树至少为2个,且第1个子树的根结点必为b(由剩下的先序遍历结点序列bejkcfghid可得),再由剩下的后序遍历结点序列jkebfghicd可知,第一个子树由结点集合{jkeb}组成;而在先序遍历结点序列bejkcfghid中位于第一个子树结点集合{bejk}后的第一个结点是c,因此可推导出第二个子树的根结点必为c,再由后序遍历结点序列jkebfghicd可知其结点集合为{cfghi};同理可得第三个子树的结点集合为{d},因此,根结点a的有3个子树,因为是13叉树,所以这3个子树的形态有 种组合方式。
        第一个子树由先序遍历结点序列bejk和后序遍历结点序列jkeb组成,设符合条件的子树数为m1;
        第二个子树由先序遍历结点序列cfghi和后序遍历结点序列fghic组成,设符合条件的子树数为m2;
        第三个子树由先序遍历结点序列d和后序遍历结点序列d组成,因此d为叶结点,设符合条件的子树数为1;
        M1和m2的值求解同样也是由先序和后序遍历求符合条件的13叉树个数的问题,按照上述思路可递归实现,得 ,因此本题满足条件的13叉树的个数为:
        
        总结:已知n叉树的先序和后序遍历,求符合条件的n叉树的个数,解题策略为:
        1、设符合条件的n叉树的个数为sum,初值为1;
        2、根据n叉树的先序遍历求出根结点,根结点的子树数为k(初值为0),n叉树结点个数为m;
        3、找出先序遍历中根结点后一个结点和后序遍历中根结点前一个结点,如果这两个结点相同,则n叉树只有一个子树(k=1),从树的形态上讲,这个子树可以是根结点的第1个子树或第2个子树……或第n个子树,因此共有种;
        4、如果这两个结点不相同,则说明根结点存在多个子树;从后序遍历的第一个结点开始找与先序遍历中根结点后一个结点相同的结点,并记下位置t1,则后序遍历1~ t1之间的结点和先序遍历2~ t1+1之间的结点构成了根结点的第一个子树(k=1);接着从后序遍历的第t1+1个结点开始找与先序遍历中第t1+2结点相同的结点,并记下位置t2,则后序遍历t1+1~ t2之间的结点和先序遍历t1+2~ t2+1之间的结点构成了根结点的第二个子树(k=2);若t2+1<m,则根结点还有其它子树,按上述方法重复查找,直到t2+1=m。则根结点的k个子树全部确定,其形状排列方式共有种;
        5、若根结点的k个子树只有一个结点,则结束求解,否则对根结点的k个子树按本解题策略分别进行递归求解,求解其符合条件的子树的个数sum1、sum2、sum3……、sumk;则
其实总结起来就是分析每个树有多少个子树,递归思想可以解决。
注意排列方法数求解过程,不要做重复计算,否则肯定会超时。
  1.     private static void CaculateTree(int n, String preOrder, String postOrder) {  
  2.         int len = preOrder.length();  
  3.         if (len == 1) {  
  4.             return;  
  5.         }  
  6.         int count = 0;  
  7.         preOrder = preOrder.substring(1);  
  8.         postOrder = postOrder.substring(0,len-1);  
  9.         while (!"".equals(preOrder)) {  
  10.             int index = postOrder.indexOf(preOrder.charAt(0))+1;  
  11.             String newPre = preOrder.substring(0,index);  
  12.             String newPost = postOrder.substring(0,index);  
  13.             preOrder = preOrder.substring(index);  
  14.             postOrder = postOrder.substring(index);  
  15.             count++;  
  16.             CaculateTree(n, newPre, newPost);  
  17.         }  
  18.         num *= CaculateCom(count, n);  
  19.     }  
07long long test(string pre, string post) {
08    long long sum = 1;
09    int num = 0;
10     int k = 0, i;
11    pre.erase(pre.begin());
12    post=post.substr(0, post.length()-1);
13    while (k < pre.length()) {
14        for (i = 0; i < post.length(); i++)
15            if (pre[k] == post[i]) {
16                sum *= test(pre.substr(k, i - k + 1),
17                        post.substr(k, i - k + 1));
18                num++; //num代表串被分成了几段(例如 (bejkcfghid,jkebfghicd) = (bejk, cfghi, d) )
19                k = i + 1;
20                break;
21            }
22    }
23    //cout << pre << "  " << post <<"  " << t1 << " =" << num << endl << endl;
24    sum *= c[num][n]; //从n中取num个的取法个数
25    return sum;
26}

21int getCnt(string left,string right){
22    int cnt=0;
23    int res = 1;
24    if(left.size() <= 1) return n; //只有一个元素,可以放置n个位置
25    for(int i=0; i<left.length();){
26        int j=i;
27        while(j<left.length() && right[j] != left[i]) j++ ;
28        //一层的单个叶子节点不考虑
29        if(j>i)
30            res *= getCnt(left.substr(i+1,j-i), right.substr(i,j-i));
31        cnt++;
32        i = j+1;
33    }
34    res *= c[n][cnt];
35    return res;
36}
Read full article from 九度-1044-Pre-Post[分治和组合数] | Acm之家

Labels

LeetCode (1432) GeeksforGeeks (1122) LeetCode - Review (1067) Review (882) Algorithm (668) to-do (609) Classic Algorithm (270) Google Interview (237) Classic Interview (222) Dynamic Programming (220) DP (186) Bit Algorithms (145) POJ (141) Math (137) Tree (132) LeetCode - Phone (129) EPI (122) Cracking Coding Interview (119) DFS (115) Difficult Algorithm (115) Lintcode (115) Different Solutions (110) Smart Algorithm (104) Binary Search (96) BFS (91) HackerRank (90) Binary Tree (86) Hard (79) Two Pointers (78) Stack (76) Company-Facebook (75) BST (72) Graph Algorithm (72) Time Complexity (69) Greedy Algorithm (68) Interval (63) Company - Google (62) Geometry Algorithm (61) Interview Corner (61) LeetCode - Extended (61) Union-Find (60) Trie (58) Advanced Data Structure (56) List (56) Priority Queue (53) Codility (52) ComProGuide (50) LeetCode Hard (50) Matrix (50) Bisection (48) Segment Tree (48) Sliding Window (48) USACO (46) Space Optimization (45) Company-Airbnb (41) Greedy (41) Mathematical Algorithm (41) Tree - Post-Order (41) ACM-ICPC (40) Algorithm Interview (40) Data Structure Design (40) Graph (40) Backtracking (39) Data Structure (39) Jobdu (39) Random (39) Codeforces (38) Knapsack (38) LeetCode - DP (38) Recursive Algorithm (38) String Algorithm (38) TopCoder (38) Sort (37) Introduction to Algorithms (36) Pre-Sort (36) Beauty of Programming (35) Must Known (34) Binary Search Tree (33) Follow Up (33) prismoskills (33) Palindrome (32) Permutation (31) Array (30) Google Code Jam (30) HDU (30) Array O(N) (29) Logic Thinking (29) Monotonic Stack (29) Puzzles (29) Code - Detail (27) Company-Zenefits (27) Microsoft 100 - July (27) Queue (27) Binary Indexed Trees (26) TreeMap (26) to-do-must (26) 1point3acres (25) GeeksQuiz (25) Merge Sort (25) Reverse Thinking (25) hihocoder (25) Company - LinkedIn (24) Hash (24) High Frequency (24) Summary (24) Divide and Conquer (23) Proof (23) Game Theory (22) Topological Sort (22) Lintcode - Review (21) Tree - Modification (21) Algorithm Game (20) CareerCup (20) Company - Twitter (20) DFS + Review (20) DP - Relation (20) Brain Teaser (19) DP - Tree (19) Left and Right Array (19) O(N) (19) Sweep Line (19) UVA (19) DP - Bit Masking (18) LeetCode - Thinking (18) KMP (17) LeetCode - TODO (17) Probabilities (17) Simulation (17) String Search (17) Codercareer (16) Company-Uber (16) Iterator (16) Number (16) O(1) Space (16) Shortest Path (16) itint5 (16) DFS+Cache (15) Dijkstra (15) Euclidean GCD (15) Heap (15) LeetCode - Hard (15) Majority (15) Number Theory (15) Rolling Hash (15) Tree Traversal (15) Brute Force (14) Bucket Sort (14) DP - Knapsack (14) DP - Probability (14) Difficult (14) Fast Power Algorithm (14) Pattern (14) Prefix Sum (14) TreeSet (14) Algorithm Videos (13) Amazon Interview (13) Basic Algorithm (13) Codechef (13) Combination (13) Computational Geometry (13) DP - Digit (13) LCA (13) LeetCode - DFS (13) Linked List (13) Long Increasing Sequence(LIS) (13) Math-Divisible (13) Reservoir Sampling (13) mitbbs (13) Algorithm - How To (12) Company - Microsoft (12) DP - Interval (12) DP - Multiple Relation (12) DP - Relation Optimization (12) LeetCode - Classic (12) Level Order Traversal (12) Prime (12) Pruning (12) Reconstruct Tree (12) Thinking (12) X Sum (12) AOJ (11) Bit Mask (11) Company-Snapchat (11) DP - Space Optimization (11) Dequeue (11) Graph DFS (11) MinMax (11) Miscs (11) Princeton (11) Quick Sort (11) Stack - Tree (11) 尺取法 (11) 挑战程序设计竞赛 (11) Coin Change (10) DFS+Backtracking (10) Facebook Hacker Cup (10) Fast Slow Pointers (10) HackerRank Easy (10) Interval Tree (10) Limited Range (10) Matrix - Traverse (10) Monotone Queue (10) SPOJ (10) Starting Point (10) States (10) Stock (10) Theory (10) Tutorialhorizon (10) Kadane - Extended (9) Mathblog (9) Max-Min Flow (9) Maze (9) Median (9) O(32N) (9) Quick Select (9) Stack Overflow (9) System Design (9) Tree - Conversion (9) Use XOR (9) Book Notes (8) Company-Amazon (8) DFS+BFS (8) DP - States (8) Expression (8) Longest Common Subsequence(LCS) (8) One Pass (8) Quadtrees (8) Traversal Once (8) Trie - Suffix (8) 穷竭搜索 (8) Algorithm Problem List (7) All Sub (7) Catalan Number (7) Cycle (7) DP - Cases (7) Facebook Interview (7) Fibonacci Numbers (7) Flood fill (7) Game Nim (7) Graph BFS (7) HackerRank Difficult (7) Hackerearth (7) Inversion (7) Kadane’s Algorithm (7) Manacher (7) Morris Traversal (7) Multiple Data Structures (7) Normalized Key (7) O(XN) (7) Radix Sort (7) Recursion (7) Sampling (7) Suffix Array (7) Tech-Queries (7) Tree - Serialization (7) Tree DP (7) Trie - Bit (7) 蓝桥杯 (7) Algorithm - Brain Teaser (6) BFS - Priority Queue (6) BFS - Unusual (6) Classic Data Structure Impl (6) DP - 2D (6) DP - Monotone Queue (6) DP - Unusual (6) DP-Space Optimization (6) Dutch Flag (6) How To (6) Interviewstreet (6) Knapsack - MultiplePack (6) Local MinMax (6) MST (6) Minimum Spanning Tree (6) Number - Reach (6) Parentheses (6) Pre-Sum (6) Probability (6) Programming Pearls (6) Rabin-Karp (6) Reverse (6) Scan from right (6) Schedule (6) Stream (6) Subset Sum (6) TSP (6) Xpost (6) n00tc0d3r (6) reddit (6) AI (5) Abbreviation (5) Anagram (5) Art Of Programming-July (5) Assumption (5) Bellman Ford (5) Big Data (5) Code - Solid (5) Code Kata (5) Codility-lessons (5) Coding (5) Company - WMware (5) Convex Hull (5) Crazyforcode (5) DFS - Multiple (5) DFS+DP (5) DP - Multi-Dimension (5) DP-Multiple Relation (5) Eulerian Cycle (5) Graph - Unusual (5) Graph Cycle (5) Hash Strategy (5) Immutability (5) Java (5) LogN (5) Manhattan Distance (5) Matrix Chain Multiplication (5) N Queens (5) Pre-Sort: Index (5) Quick Partition (5) Quora (5) Randomized Algorithms (5) Resources (5) Robot (5) SPFA(Shortest Path Faster Algorithm) (5) Shuffle (5) Sieve of Eratosthenes (5) Strongly Connected Components (5) Subarray Sum (5) Sudoku (5) Suffix Tree (5) Swap (5) Threaded (5) Tree - Creation (5) Warshall Floyd (5) Word Search (5) jiuzhang (5)

Popular Posts