zoukankan      html  css  js  c++  java
  • Cow Pedigrees(△)

    想到的dp

    但是思路不对没有想到利用乘法原理。

    设二叉树的高度为k,其中的节点个数为n

    则可能的二叉树个数

    f[k][n] = 2 * 求和(f[k - 1][r]*smaller[k - 1][n – 1 - r])+ 求和(f[k - 1][r]*f[k - 1][n – 1 - r])

    其中r的范围为从1到n

    第一项表示,左子树高度为k-1,右子树高度小于k-1,乘以2,表示左右子树对换的情况。

    第二项表示,左右子树的高度都是k-1

    这里需要注意的是smaller的计算,smaller[k][n]表示的是高度比k小,节点个数为n的子数可能种类。

    USACO的分析解答:

    This is a DP problem. The properties of a tree that we are interested in are depth and number of nodes, so we'll make a table: table[i][j] contains the number of trees with depth i and number of nodes j. Given the constraints of the task, j must be odd. How do you construct a tree? From smaller trees, of course. A tree of depth i and j nodes will be constructed from two smaller trees and one more node.

    With i and j already chosen, we chose k, which is the number of nodes in the left subtree. Then the number of nodes in the right subtree is known, j-k-1. For depth, at least one subtree has to have depth i-1 so that the new made tree would have depth i. There are three possibilities: the left subtree can have depth i-1 and the depth of the right subtree can be smaller, the right subtree can have depth i-1 and the depth of the left subtree can be smaller, or they can both have depth i-1.

    The truth is that once we are constructing trees of depth i, we use smaller trees, but we only care if those are of depth i-1 or smaller. So, let another array, smalltrees[i-2][j] contain number of trees of any depth smaller than i-1, not just i-2. Now, knowing all this, we contruct our tree from three possible ways:

    table[i][j] += smalltrees[i-2][k]*table[i-1][j-1-k];
                      // left subtree smaller than i-1, right is i-1
    table[i][j] += table[i-1][k]*smalltrees[i-2][j-1-k];
                      // left subtree is i-1, right smaller
    table[i][j] += table[i-1][k]*table[i-1][j-1-k];
                      // both i-1 

    In addition, if the number of nodes in the left subtree is smaller then the number of nodes in the left subtree, we can count the tree twice, as different tree can be constructed by swapping left and right subtree.

    Total running time is O(K*N^2),with very favorable constant factor.

  • 相关阅读:
    【shell】日志切割
    【PHP】SVN版本差异导出
    Linux服务器上安装JDK
    Linux 下node环境安装
    CentOS 7.3安装mariadb
    Centos 7.4 自动初始化docker环境,配置docker镜像仓库
    Shell 模板 (Yes or NO)
    Linux修改时间和时区
    lvm方式挂载盘及扩容
    安装ansible
  • 原文地址:https://www.cnblogs.com/growup/p/2073893.html
Copyright © 2011-2022 走看看