And a secondary scan distance transducers root tree 1405 method

 

1405 Tree and distance

The meaning of problems: given an unrooted trees, it is assumed that there are n nodes, nodes numbered from 1 to n, seek distance (shortest path) and between any two points.

Thinking: open array size records each node and its child node size of the collection used to record the sum open during dfs distance from the root node to the child node, which is used to record the distance of each node and the prefix, f to from all other nodes.

 

2 dfs reasons:

First: dfs we seek downwardly from the root node to the root prefix from each child node and, with the sum of the logs and each node we sum to the f [1] to determine the root node to all nodes and the. Back simultaneously obtains the size of each subset of nodes, a record size.

Second dfs: 1 distance to other known root node and then still known size of each subset of nodes, how to find the rest of the distance to each node and other nodes? Transfer the root may be utilized.

 

 

 As shown, if transferred to the root node 2, from the first to reduce size [2] * 1, and then to increase the (n-size [2]) * 1, because the root node 2 changes, one to two child nodes of the node set all distance to disappear, i.e. the red part (size [v]), to increase the distance from node 2 to node a subset of the green part is (n-size [v]), to obtain a state transition equation:

f[v]=f[u]+n-size[v]*2

 

 

#include<bits/stdc++.h>
using namespace std;
#define ll long long
const int maxn=1e5+10;
int head[2*maxn],ver[2*maxn],nxt[2*maxn];
int tot=0;
int n;
ll sum[maxn],size[maxn],f[maxn];
void add(int u,int v)
{
    ver[++tot]=v;
    nxt[tot]=head[u];
    head[u]=tot;
}

void dfs1(int u,int fa)
{
    size[u]=1;
    for(int i=head[u]; i; i=nxt[i])
    {
        int v=ver[i];
        if(v==fa) continue;
        sum[v]=sum[u]+1;
        f[1]+=sum[v];
        dfs1(v,u);
        size[u]+=size[v];
    }
}

void dfs2(int u,int fa)
{
    for(int i=head[u]; i; i=nxt[i])
    {
        int v=ver[i];
        if(v==fa) continue;
        f[v]=f[u]+n-2*size[v];
        dfs2(v,u);
    }


}
int main()
{
    scanf("%d",&n);
    for(int i=1; i<=n-1; i++)
    {
        int u,v;
        scanf("%d%d",&u,&v);
        add(u,v);
        add(v,u);
    }
    dfs1(1,0);
    dfs2(1,0);
    for(int i=1; i<=n; i++)
        printf("%lld\n",f[i]);
}

 

Guess you like

Origin www.cnblogs.com/dongdong25800/p/11127307.html