2019-03-28 15:25:43

问题描述:

问题求解:

写过的最好的Hard题之一。

初看本题,很经典的路径和嘛,dfs一遍肯定可以得到某个节点到其他所有节点的距离和。这种算法的时间复杂度是O(n ^ 2)。看一下数据量,emmm,果然不行。这个数据量一看就知道只能是O(n)的算法了。

只遍历一遍最多只能得到一个解,因此本题肯定是需要遍历至少两遍的。

在第一遍遍历的时候我们需要保存下两个值,一个是当前节点的subtree的路径总和,一个是当前节点的subtree的总的节点数。

在第二遍遍历的时候,我们已经知道root节点的值已经是最终的结果了,这个时候当我们将根节点从root移动到其child的时候,有cnt[child]的节点数的离现在的根节点近了一步,有N - cnt[child]的节点到当前根节点远了一步,所以res[child] = res[root] - cnt[child] + N - cnt[child]。这样再次遍历所有节点更新res数组得到的结果就是我们需要的最终的答案。

    public int[] sumOfDistancesInTree(int N, int[][] edges) {
List<Set<Integer>> graph = new ArrayList<>();
int[] res = new int[N];
int[] cnt = new int[N];
for (int i = 0; i < N; i++) graph.add(new HashSet<>());
for (int[] edge : edges) {
graph.get(edge[0]).add(edge[1]);
graph.get(edge[1]).add(edge[0]);
}
dfs1(0, -1, res, cnt, graph);
dfs2(0, -1, res, cnt, graph);
return res;
} private void dfs1(int root, int parent, int[] res, int[] cnt, List<Set<Integer>> graph) {
for (int node : graph.get(root)) {
if (node == parent) continue;
dfs1(node, root, res, cnt, graph);
cnt[root] += cnt[node];
res[root] += res[node] + cnt[node];
}
cnt[root] += 1;
} private void dfs2(int root, int parent, int[] res, int[] cnt, List<Set<Integer>> graph) {
for (int node : graph.get(root)) {
if (node == parent) continue;
res[node] = res[root] - cnt[node] + cnt.length - cnt[node];
dfs2(node, root, res, cnt, graph);
}
}

2019-04-17 14:26:20

    public int[] sumOfDistancesInTree(int N, int[][] edges) {
List<Set<Integer>> graph = new ArrayList<>();
for (int i = 0; i < N; i++) graph.add(new HashSet<>());
for (int[] edge : edges) {
graph.get(edge[0]).add(edge[1]);
graph.get(edge[1]).add(edge[0]);
}
int[] res = new int[N];
int[] cnt = new int[N];
int[] used = new int[N];
used[0] = 1;
dfs1(graph, 0, res, cnt, used);
Arrays.fill(used, 0);
used[0] = 1;
dfs2(graph, 0, res, cnt, used);
return res;
} private int[] dfs1(List<Set<Integer>> graph, int root, int[] res, int[] cnt, int[] used) {
res[root] = 0;
cnt[root] = 1;
for (int node : graph.get(root)) {
if (used[node] == 1) continue;
used[node] = 1;
int[] r = dfs1(graph, node, res, cnt, used);
res[root] += r[0] + r[1];
cnt[root] += r[1];
}
return new int[]{res[root], cnt[root]};
} private void dfs2(List<Set<Integer>> graph, int root, int[] res, int[] cnt, int[] used) {
for (int node : graph.get(root)) {
if (used[node] == 1) continue;
used[node] = 1;
res[node] = res[root] + cnt[0] - cnt[node] * 2;
dfs2(graph, node, res, cnt, used);
}
}

  

树中的路径和 Sum of Distances in Tree的更多相关文章

  1. 834. Sum of Distances in Tree —— weekly contest 84

    Sum of Distances in Tree An undirected, connected tree with N nodes labelled 0...N-1 and N-1 edges a ...

  2. [Swift]LeetCode834. 树中距离之和 | Sum of Distances in Tree

    An undirected, connected tree with N nodes labelled 0...N-1 and N-1 edges are given. The ith edge co ...

  3. [LeetCode] 834. Sum of Distances in Tree 树中距离之和

    An undirected, connected tree with N nodes labelled 0...N-1 and N-1 edges are given. The ith edge co ...

  4. [LeetCode] 834. Sum of Distances in Tree

    LeetCode刷题记录 传送门 Description An undirected, connected treewith N nodes labelled 0...N-1 and N-1 edge ...

  5. 【leetcode】834. Sum of Distances in Tree(图算法)

    There is an undirected connected tree with n nodes labeled from 0 to n - 1 and n - 1 edges. You are ...

  6. leetcode834 Sum of Distances in Tree

    思路: 树形dp. 实现: class Solution { public: void dfs(int root, int p, vector<vector<int>>& ...

  7. [LeetCode] 112. Path Sum ☆(二叉树是否有一条路径的sum等于给定的数)

    Path Sum leetcode java 描述 Given a binary tree and a sum, determine if the tree has a root-to-leaf pa ...

  8. CodeChef Sum of distances(分治)

    CodeChef Sum of distances(分治) 题目大意 有一排点,每个点 i 向 \(i + 1, i + 2, i + 3\) 分别连价值为 \(a_i,b_i,c_i\) 的有向边, ...

  9. Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum. For example: Given the below binary tree andsum =

    Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all ...

随机推荐

  1. git上clone需要ssh时

    在命令行中输入ssh-keygen -t rsa -C "your_email@example.com" 然后使用编辑器打开id_rsa.pub文件,复制里面的ssh

  2. 微信公众平台开发教程(一)_微信接入校验以及token获取

    微信公众平台是运营者通过公众号为微信用户提供资讯和服务的平台,而公众平台开发接口则是提供服务的基础. 接入微信公众平台开发,开发者需要按照如下步骤完成: 1.填写服务器配置 2.验证服务器地址的有效性 ...

  3. 阿里云HttpClient跨天之后解析不了域名

    也许这是一个少见的情况,我使用HttpClient写了一个调用第三方服务的请求,在本机测试和腾讯云上测试都没有问题,但是放到阿里云之后,刚启动的时候是没有问题的,但是每次过零点之后,就会报异常: ja ...

  4. 零门槛,包教会。让你在5分钟内使用以太坊ERC20智能合约发行属于自己的空气币

    前言 目前区块链是互联网中最最火的风口,没有之一.我周围的很多朋友也加入了“炒币”行列,但很不幸,几乎都被“割韭菜”了.而经过我的几天研究,发现,如果自己要发行一种空气币,简直太简单了.只需要下面几个 ...

  5. 7zip 18.3性能测试

    配置 7zip 18.3 bate3 的性能大幅提升,进行一点简单测试 配置为 E3 1230v2 3.5G 4核心/8线程 12G内存 均为8线程测试 压缩解压一个1.5G的虚拟机磁盘镜像 测试 再 ...

  6. 2017-2018-2 『网络对抗技术』Exp1:PC平台逆向破解 20165335

    一.实验目标: 本次实践的对象是一个名为pwn1的linux可执行文件. 该程序正常执行流程是:main调用foo函数,foo函数会简单回显任何用户输入的字符串. 该程序同时包含另一个代码片段,get ...

  7. (Review cs231n) Spatial Localization and Detection(classification and localization)

     重在图像的定位和检测的内容. 一张图片中只有一种给定类别标签的对象,定位则是图像中有对象框:再这些类中,每一个训练目标都有一个类和许多的图像内部对应类的位置选框. 猜想的仅是类标签,不如说它们是位置 ...

  8. 用 webpack 创建 vue 项目

    1.安装支持webpack 包 npm i -D  webpack webpack-cli  aspnet-webpack webpack-dev-middleware  webpack-hot-mi ...

  9. 20180519001 - DataTable Group by功能参考

    DataSet6 = DataSet1.Copy(); DataRow[] dr = DataSet6.Tables[0].Select(" 完工状态 = '完工异常' "); D ...

  10. Maven Webapp项目web.xml版本记录

    web.xml 2.0版本 <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3// ...