2019 A title race Jiangxi solution to a problem with the code

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<string>
#include<cstring>
using namespace std;
typedef long long ll;
const int N=100010;
const int inf=0x3f3f3f3f;
int h[N],ne[N],idx;
int st[N];
int n;
int tot;
struct node{
    int u;
    int v;
    int to;
};
node e[2*n];
void add(int a,int b){
    e[idx].u=a;
    e[idx].v=b;
    e[idx].to=h[a];
    h[a]=idx++;
}
void dfs(int u){
    int i;
    if(st[u])
    return ;
    st[u]=true;
    tot++;
    for(i=h[u];i!=-1;i=e[i].to)
    dfs(e[i].v);
}
int p,tmp;
int dfs1(int u,int fa,int n){
    int i;
    int tot=0;
    int sum=0;
    int ans=0;
    for(i=h[u];i!=-1;i=e[i].to){
        int j=e[i].v;
        if(j==fa)
        continue;
       to = dfs1 (j, u, n);
       years = max (years earlier);
       sum + = all;
    }
    ans=max(ans,n-sum-1);
    if(ans<tmp){
        tmp = years;
        p=u;
    }
    return sum+1;
}
ll res;

int dfs2(int u,int fa){
    int i;
    int t=0;
    int sum=0;
    for(i=h[u];i!=-1;i=e[i].to){
        int j=e[i].v;
        if(j==fa)
        continue;
        t=dfs2(j,u);
        res+=(1ll*t)*(1ll*(n-t));
        sum+=t;
    }
    return sum+1;
}

int main () {
    scanf("%d",&n);
    memset(h,-1,sizeof h);
    int i;
    int u,v;
    for(i=0;i<n-2;i++){
        scanf("%d%d",&u,&v);
        add(u,v);
        add(v,u);
    }
    int root1,root2,n1,n2;
    for(i=1;i<=n;i++){
        if(!st[i]){
            to = 0 ;
            dfs(i);
            if(i==1){
             root1=1;
             n1 = to;
            }
            else{
                root2=i;
                n2 = to;
            }
        }
    }
    int g1,g2;
    tmp=inf;
    dfs1 (root1, - 1 , n 1);
    g1=p;
    tmp=inf;
    dfs1(root2,-1,n2);
    g2=p;
    add(g1,g2);
    add(g2,g1);
    dfs2(1,-1);
    printf("%lld\n",res);
    return 0;
}
View Code

 

This is to solve the tree problem is the focus on the nature of the problem tree dp dynamic programming among.

Is connected to the center of gravity Solving dfs are two trees by solving the merged tree and the distance

And expressed as the product from the left node and a right node number of each edge (considering this contribution on the sides of each path of the two points)

Is defined as the center of gravity of the tree is removed after the point section Unicom subtree maximum number of points the minimum point.

nature:

1. The center of gravity of each tree has at most two, if both the center of gravity exists two adjacent center of gravity will.

2. The center of gravity of the two trees in two trees combined center of gravity of the connection.

 

 

Guess you like

Origin www.cnblogs.com/ctyakwf/p/12003509.html