思路:这题最朴素的想法就是,枚举根节点,每次枚举都dfs求一下其余节点的深度和。这样的话时间复杂度O(n²),绝壁tle。
那该怎么优化呢?
我们设dp[rt]表示以rt为根的树的所有节点的深度和。
我们注意到,如果我们求出了某个dp[rt],那么对于rt的任意一个孩子节点child,dp[child]是可以通过O(1)时间求出来的。
具体求法,我们在dp[rt]中是以rt为根,如果我们把根换成child,那么child所在子树的所有节点,对深度和的贡献都会减1,而除了child所在子树外的节点,贡献会加1 .(可以画图理解一下)
所以: dp[child]=dp[rt] - num[child] + n - num[child] (num[i]表示以i为根的子树包含的总节点)
那么我们只要先求出任意一个dp[rt] 然后dfs一遍求其余dp[i]就可以了 .O(n)
//#pragma comment(linker, "/STACK:102400000,102400000")//手动扩栈
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<stdlib.h>
#include<string.h>
#include<string>
#include<vector>
#include<stack>
#include<queue>
#include<map>
#include<math.h>
#include<set>
#include<unordered_map>
using namespace std;
#define LL long long
#define ULL unsigned long long
const int INF=0x3f3f3f3f;
const double eps=1e-5