Description
Given a tree without root, suppose it has n nodes, the node number from 1 to N, the sum of the distances between any two points (shortest path).
Input
The first row contains a positive integer n (n <= 100000), representing the number of nodes.
The back (n-1) line, two integers per line representing the edge of the tree.
Output
One integer per line, and the first (i = 1,2,... N) row represents the sum of the distances of all nodes to point I.
Input Sample
4
1 2
3 2 4 2
Output Sample
5
3
5
5
train of Thought
We selected Node 1 1 as the root, Des[i] des[i] represents the number of nodes of a subtree with I I as the root, Ans[i] ans[i] represents the distance of all nodes to I
For the root node, the ans[1] ans[1 equals the sum of the depth of all nodes, so we can first get ans[1] ans[1]
Subsequently, for the child node of x x to, ans[to]=ans[x]−des[to]+ (N−des[to]) ans[to]=ans[x]-des[to]+ (n-des[to))
where −des[to]-des[to] is because a little distance to the "to" in the root subtree of the to to is less than 1 1, + (N−des[to]) + (N-des[to]) refers to the rest point distance to the distance x x more 1 1
AC Code
#include <bits/stdc++.h> using namespace std;
typedef __int64 LL;
const int MAXN = 1E5+10;
struct node {int to;
int next;
} edge[maxn<<1];
int head[maxn],tot,n;
int DES[MAXN];
LL ANS[MAXN];
void Init () {memset (ans,0,sizeof (ans));
memset (des,0,sizeof (DES));
Memset (head) (head,-1,sizeof);
tot=0;
} void Addedge (int u,int v) {edge[tot].to=v;
Edge[tot].next=head[u];
head[u]=tot++;
} void dfs1 (int x,int fa,int deep) {des[x]=1;
Ans[1]+=deep;
for (int i=head[x]; I!=-1 i=edge[i].next) {int to=edge[i].to;
if (TO!=FA) {DFS1 (to,x,deep+1);
Des[x]+=des[to];
}} void dfs2 (int x,int fa) {for (int i=head[x]; i!=-1; i=edge[i].next) {int to=edge[i].to;
if (TO!=FA) {Ans[to] = ans[x]-des[to]+ (n-des[to));
DFS2 (TO,X);
int main () {Ios::sync_with_stdio (false);
Init ();
cin>>n; Forint i=1; i<n;
i++) {int u,v;
cin>>u>>v;
Addedge (U,V);
Addedge (V,u);
} DFS1 (1,-1,0);
DFS2 (1,-1);
for (int i=1; i<=n; i++) cout<<ans[i]<<endl;
return 0; }