P1229 遍历问题

题目传送门

一、已知后序+中序,求前序

https://www.cnblogs.com/littlehb/p/15088998.html

二、已知前序+中序,求后序

https://www.cnblogs.com/littlehb/p/15088448.html

三、已知前序+后序,求中序个数

只有一个儿子的节点 才会在知道 前序后序的情况下有不同的中序遍历,所以将题目转化成找只有一个儿子的节点个数。

可以很容易的找出这类节点在前序后序中出现的规律。(前序中出现AB,后序中出现BA,则这个节点只有一个儿子)

每个这类节点有两种中序遍历(及儿子在左,儿子在右)根据乘法原理中序遍历数为 2^节点个数种

#include <bits/stdc++.h>

using namespace std;
const int N = 100010;
int ans = 1;//最少一种中序排列
string a, b;


int main() {
    cin >> a >> b;
    for (int i = 0; i < a.size() - 1; i++) {
        string t = a.substr(i, 2); // 截取相邻的两个字符串
        reverse(t.begin(), t.end()); // 反转
        if (b.find(t) != string::npos) ans *= 2; // 匹配成功则总数*2
    }
    cout << ans << endl;
    return 0;
}
posted @ 2021-08-04 17:09  糖豆爸爸  阅读(108)  评论(0编辑  收藏  举报
Live2D