CodeForces-1671E Preorder

Preorder#

树型 dp + 思维

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

状态转移方程:

  • 当左右子树不同,两个子树交换位置之后,没有重复的出现:dp[x]=dp[lson]dp[rson]2

  • 当左右子树相同时,两个子树交换位置后,会有相同的出现:dp[x]=dp[lson]dp[rson]

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

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

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

时间复杂度应该是 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;
}
posted @   dgsvygd  阅读(25)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示
主题色彩