lintcode1403 · 最大乘积路径【中等 DFS】

题目

https://www.lintcode.com/problem/1403

一棵有 n 个结点,根结点为 1 的二叉树,每条边通过两个顶点x[i],y[i]来描述,每个点的权值通过d[i]来描述。
求从根结点到叶子结点路径上所有结点权值乘积对1e9+7取模后最大的路径的值。

2 <= n <= 10^5
-10^5 <= d[i] <= 10^5
1 <= x[i], y[i] <= n
样例
样例 1:

输入:x = [1], y = [2], d = [1,1]
输出:1。
解释:最大乘积路径:1->2(1 * 1) % (1e9+7) = 1
样例 2:

输入: x =[1,2,2], y = [2,3,4], d = [1,1,-1,2]
输出:1000000006。
解释:最大乘积路径:1->2->3(1 * 1 * ( -1 )) % (1e9+7) = 1000000006

思路

    简单来说就是以及其纠结的方式给你了一个binary tree,
    然后要求出从根结点到叶子结点路径上所有结点权值乘积对1e9+7取模后。
    因为树太深的情况下会溢出,所以每次乘积都要 [(product + mod) % mod]

答案

public class Solution {
    /**
     * @param x: The end points of edges set
     * @param y: The end points of edges set
     * @param d: The weight of points set
     * @return: Return the maximum product
     */
    public int getProduct(int[] x, int[] y, int[] d) {
           /*
        简单来说就是以及其纠结的方式给你了一个binary tree,
        然后要求出从根结点到叶子结点路径上所有结点权值乘积对1e9+7取模后。
        因为树太深的情况下会溢出,所以每次乘积都要 [(product + mod) % mod]
         */
        Map<Integer, List<Integer>> map = new HashMap<>();
        for (int i = 0; i <x.length ; i++) {
            if(!map.containsKey(x[i]))
                map.put(x[i],new ArrayList<>());

            map.get(x[i]).add(y[i]);
        }

        Map<Integer,Integer> weight = new HashMap<>();
        for (int i = 0; i <d.length ; i++) {
            weight.put(i+1,d[i]);
        }
        int[] ans ={Integer.MIN_VALUE};
        f(1,map,weight,d[0],ans);
        return ans[0];
    }

    public static void f(int node,Map<Integer,List<Integer>> map,
                         Map<Integer,Integer> weight,long product,int[] ans){
        if(!map.containsKey(node)){
            ans[0] =(int)Math.max(ans[0],product);
            return;
        }

        int mod = 1000000007;
        for (Integer next : map.get(node)) {
           f(next,map,weight,(product*weight.get(next)+mod)%mod,ans);
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

赵长辉

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值