其他分享
首页 > 其他分享> > CodeForces-1671E Preorder

CodeForces-1671E Preorder

作者:互联网

Preorder

树型 dp + 思维

\(dp[i]\) 表示以 \(i\) 为根的子树通过变换有多少种不同的先序遍历

状态转移方程:

这里的相同并不是指原来的两个子树相同,而是指经过任意变换之后,两个子树存在相同的情况

如果存在相同的情况,说明其中一个子树的任意形态,另一个子树必然也有

接下来就考虑如何判断两个完全二叉树是否相同,最简单的就是对树进行排序后判断是否相同,看看代码就好了

时间复杂度应该是 \(O(nlogn)\)

#include <iostream>
#include <string>
using namespace std;
typedef long long ll;
const int maxn = 1 << 18 | 1;
const ll mod = 998244353;
int n;
string h[maxn], s;
ll ans[maxn];

void dfs(int now, int d)
{
    int x = now - 1;
    if(d == n)
    {
        h[now] = s[x];
        ans[now] = 1;
        return;
    }
    int lson = now << 1, rson = now << 1 | 1;
    dfs(lson, d + 1);
    dfs(rson, d + 1);
    if(h[lson] > h[rson]) swap(h[lson], h[rson]);
    h[now] = s[x] + h[lson] + h[rson];
    if(h[lson] == h[rson])
        ans[now] = ans[rson] * ans[lson] % mod;
    else
        ans[now] = ans[rson] * ans[lson] * 2 % mod;
}

int main()
{
    cin >> n >> s;
    dfs(1, 1);
    cout << ans[1] << endl;
    return 0;
}

标签:Preorder,子树,相同,rson,1671E,CodeForces,lson,ans,dp
来源: https://www.cnblogs.com/dgsvygd/p/16606936.html