zoukankan      html  css  js  c++  java
  • 823. Binary Trees With Factors (树上的动态规划)

    题意:Given an array of unique integers, each integer is strictly greater than 1.
    We make a binary tree using these integers and each number may be used for any number of times.
    Each non-leaf node's value should be equal to the product of the values of it's children.
    How many binary trees can we make?  Return the answer modulo 10 ** 9 + 7.
     

     
     
    思路: 这道题和一般动态规划题目的形式不太一样,和建树的过程结合起来,但是不要忘记了动态规划的本质是什么,就是有小问题到大问题的转化,可以将大问题分解为小问题,大问题可以由小问题组成,然后看这道题,很明显根节点和子节点是状态转化的关系;
     
    回到这题,思考c,c.left=a,c.right=b,以c为根节点能够构造的树的个数, 以c的右子节点为根节点能构造的树的个数,是什么关系?
     
    是不是dp[c] = dp[a] * dp[b]呢?因为对于每个a的树形式,和对于每个b的树形式,都是不一样的树;且a、b位交换,也是不一样的树,故正确的状态转移方程应该是:dp[c] = sum{dp[a] * dp[b]}
     
     
     
     
    代码:
    class Solution {
        public int numFactoredBinaryTrees(int[] A) {
            long res = 0;
            int N = A.length;
            long[] dp = new long[N];
            Arrays.fill(dp, 1);
            Arrays.sort(A);
            Map<Integer, Integer> map = new HashMap<>();
            for (int i = 0; i < N; i++) {
                map.put(A[i], i);
            }
            int kmod = 1_000_000_007;
    
            for (int i = 0; i < N; i++) {
                for (int j = 0; j < i; j++) {
                    if (A[i] % A[j] == 0) {
                        int right = A[i] / A[j];
                        if (map.containsKey(right)) {
                            dp[i] = (dp[i] + dp[j] * dp[map.get(right)]) % kmod;
                        }
                    }
                }
            }
            for (long num : dp) res += num;
            return (int)(res % kmod);
        }
    }
    View Code

    或者简化一下,直接用map存也是可以的:

    class Solution {
        public int numFactoredBinaryTrees(int[] A) {
            final int kmod = 1_000_000_007;
            Map<Integer, Long> map = new HashMap<>(); //dp[]
            Arrays.sort(A);
            for (int i = 0; i < A.length; i++) {
                map.put(A[i], 1L);
                for (int j = 0; j < i; j++) {
                    if (A[i] % A[j] == 0 && map.containsKey((A[i] / A[j]))) {
                        map.put(A[i], (map.get(A[i]) + map.get(A[j]) * map.get(A[i] / A[j])) % kmod);
                    }
                }
            }
            long res = 0;
            for (long num : map.values()) res += num;
            return (int) (res % kmod);
        }
    }
    View Code
     
    这题还有个坑是注意答案会很大,应该用long型保存,且最后应该求模
     
     
  • 相关阅读:
    【转】.net 在线播放各类视频
    引用母版页的内容页添加CSS文件
    NET上传大文件出现网页无法显示的问题 默认的上传文件大小是4M
    DropDownList1.Items.Insert 与 DropDownList1.Items.Add 的区别
    暑假集训8.10-网络流套树剖套线段树
    暑假集训8.10—网络流(黑白染色法)
    暑假集训8.7数据结构专题—网络流套线段树
    暑假集训8.7数据结构专题-线段树存直线
    暑假集训8.7数据结构专题-很妙的线段树( 觉醒力量(hidpower))
    可修改主席树&树上可修改主席树—树套树套树!!!
  • 原文地址:https://www.cnblogs.com/shawshawwan/p/9558306.html
Copyright © 2011-2022 走看看