Talking about the center of gravity of the tree

Talking about the diameter of the tree


definition:

  Minimum number of nodes a node tree largest subtree;

nature:

  1. Remove the resulting center of gravity of all the subtree nodes does not exceed 1/2 of the original tree, a tree with two up to the center of gravity;

  All nodes and the minimum distance of the center of gravity, the center of gravity if there are two, and they are equal distances 2. tree;

  3. The two sides of the tree by a merger, the new center of gravity in the center of gravity of the two original tree path;

  4. The tree delete or add a leaf node, only one side of the center of gravity moves up;

Solving:

  A method for solving a variety were used different definitions and properties:

  1. Definitions solving:

  SIZ [i] denotes the size of the subtree of node i DP [i] i is represented by the maximum root subtree size, Val [i] for the i-node straightaway right point, but to explain the codes

  

inline void dfs(int now,int fa)
{
    siz[now]=val[now];
    dp[now]=0;
    for(int i=head[now];i;i=a[i].nxt)
    {
        int t=a[i].to;
        if(t==fa) continue;
        dfs(t,now);
        siz[now]+=siz[t];
        dp[now]=max(dp[now],siz[t]);
    }
    dp[now]=max(dp[now],n-dp[now]);
    if(dp[now]<dp[ans]) ans=now;
}

  2. Nature solving:

  Generally defined solved enough, but sometimes more convenient and practical properties Solving;

  The nature of the 2: distance we can process all the nodes to a node, takes a minimum value;

  How obtained from a node of each node to do? In dfs down during processing it is very easy, so we can handle the first distance qwq all nodes to the root;

  SIZ [i] Ibid., F [i] represent all the child nodes of node i, and i is the distance, Val [i] Ibid., a [i] .val to the right side, 1 is set as a root node;

  

inline void dfs1(int now,int fa,int deep)
{
    siz[now]=val[now];
    dep[now]=deep;
    for(int i=head[now];i;i=a[i].nxt)
    {
        int t=a[i].to;
        if(t==fa) continue;
        dfs1(t,now,deep+a[i].val);
        siz[now]+=siz[t];
        f[now]+=f[t]+siz[t]*a[i].val;
    }
}

 

  For process f appreciated that the array: all child nodes t to t + distance now all nodes of the current sub-tree of the distance to now.

  This is obtained from the root and we then recursive other nodes of the root node through the distance and, following publicity:

  f [ now ] = f [ fa ] +( siz [ 根节点 ] - 2 * siz [ now ])* 边权;(now!= 根节点)

 

  理解如下:

  对于now的子节点,每个节点的距离减少了一个边权,总距离减少 siz [ now ] * 边权 ,对于非v子节点,每个节点距离增加了一个边权,总距离增加(siz[ 根 ]-siz [ now ])*边权

  

inline void dfs2(int now,int fa)
{
    if(now^root) f[now]=f[fa]+siz[1]-2*siz[now];
    if(f[now]<sum) res=now,sum=f[now];
    for(int i=head[now];i;i=a[i].nxt)
    {
        int t=a[i].to;
        if(t==fa) continue;
        dfs2(t,now); 
    }
}

 

  to be continue……

 

Guess you like

Origin www.cnblogs.com/knife-rose/p/11258403.html