Provincial tournament E- tree dp count - in other secondary scanning root +

Here Insert Picture Description
After secondary school last night, scanning, only to find a tree dp provincial title race was able to use this to write.

We F [u] represents: u is the node number of the root path increments. And calculate the contribution of each of these paths between.

void dfs1(int u, int fa){

    for(int i=0; i<v[u].size(); i++){
        int to=v[u][i];
        if(to==fa){
            continue;
        }

        dfs1(to, u);
        if(u>to){
            s[u]+=f[u]*(f[to]+1);
            f[u]+=(f[to]+1);
        }
    }
}

Why time is calculated
S [U] + = f [U] * (f [to] +1);
f [U] + = (f [to] +1);
we have to prove it:
Here Insert Picture Description
the same way as secondary scanning .

#include <bits/stdc++.h>
#define LL long long
using namespace std;
vector<int> v[200005];
LL s[200005];
LL f[200005];
void dfs1(int u, int fa){

    for(int i=0; i<v[u].size(); i++){
        int to=v[u][i];
        if(to==fa){
            continue;
        }

        dfs1(to, u);
        if(u>to){
            s[u]+=f[u]*(f[to]+1);
            f[u]+=(f[to]+1);
        }
    }
}

void dfs2(int u, int fa){

    if(u>fa){
        s[u]+=f[u]*(f[fa]+1);
        f[u]+=(f[fa]+1);
    }
    for(int i=0; i<v[u].size(); i++){
        int to=v[u][i];
        if(to!=fa){
            dfs2(to, u);
        }
    }
}

int main()
{
    //freopen("e1.in", "r", stdin);
    int t;scanf("%d", &t);
    while(t--){
        memset(s, 0, sizeof(s));
        memset(f, 0, sizeof(f));
        int n, u, to;
        scanf("%d", &n);
        for(int i=1; i<=n; i++){
            v[i].clear();
        }
        for(int i=1; i<=n-1; i++){
            scanf("%d%d", &u, &to);
            v[u].push_back(to);
            v[to].push_back(u);
        }
        dfs1(1, 0);
        dfs2(1, 1<<30);
        LL ans=0;
        for(int i=1; i<=n; i++){
            ans+=s[i];
        }
        printf("%lld\n", ans*2);
    }

    return 0;
}
Published 374 original articles · won praise 22 · views 20000 +

Guess you like

Origin blog.csdn.net/qq_21433411/article/details/103410861
Recommended