Perhaps a better reading experience
The center of gravity of the tree
The definition of the center of gravity of the tree
to find such a node, so that when its root node, the largest sub-tree contains the least number of nodes
The solution is simple, just pull a node as the root node, and then calculate a point when considering all finished son after his father as a child to think about the answer to a tree
Two kinds of play
int dfs (int x,int fa,int m)
{
son[x]=1,ms[x]=0;//ms max_num_of_son
int tans=2000;
for (int e=head[x];e;e=nxt[e]){
if (to[e]==fa||vis[to[e]]) continue;
int t=dfs(to[e],x,m);
if (ms[tans]>ms[t]) tans=t;
son[x]+=son[to[e]];
ms[x]=max(ms[x],son[to[e]]);
}
ms[x]=max(ms[x],m-son[x]);
if (ms[tans]>ms[x]) tans=x;
return tans;
}
int ans;
void dfs (int x,int fa,int m)
{
son[x]=1,ms[x]=0;
for (int e=head[x];e;e=nxt[e]){
if (to[e]==fa||vis[to[e]]) continue;
dfs(to[e],x,m);
son[x]+=son[to[e]];
ms[x]=max(ms[x],son[to[e]]);
}
ms[x]=max(ms[x],m-son[x]);
if (ms[ans]>ms[x]) ans=x;
return ans;
}
The diameter of the tree
Seeking a longest path in the tree
request method is not difficult, consider a point as the diameter of the turning point of
a note path and the second largest maximum path
comparing the sum of all the nodes can be both
Come true only able to save the maximum path, and then compare the current path plus the maximum path to
that is to see whether the current path is the path of the second largest or larger path
void dfs(int x,int fa) {
f[x]=1;
for (int e=head[x];e;e=nxt[e]){
if (to[e]==fa) continue;
dfs(to[e],x);
ans=max(ans,f[x]+f[to[e]]+w[e]);
f[x]=max(f[x],f[to[e]]+w[e]);
}
}
If not quite understand where to put it or there is an error, please correct me
if you like, you may wish to point a collection of praise about it