首页 > 其他 > 详细

NC15033 小G有一个大树

时间:2021-04-08 20:46:17      阅读:23      评论:0      收藏:0      [点我收藏+]

树的直径模板。

const int N=1e5+10;
vector<int> g[N];
int n;
int ans=N;
int pos;

int dfs(int u,int fa)
{
    int tot=1; // 以u为根的子树大小
    int maxchild=0;
    for(int i=0;i<g[u].size();i++)
    {
        int j=g[u][i];
        if(j == fa) continue;
        int cnt=dfs(j,u);
        maxchild=max(maxchild,cnt);
        tot+=cnt;
    }

    maxchild=max(maxchild,n-tot);
    if(maxchild < ans)
    {
        ans=maxchild;
        pos=u;
    }
    else if(maxchild == ans && u < pos)
        pos=u;
    
    return tot;
}

int main()
{
    cin>>n;

    for(int i=0;i<n-1;i++)
    {
        int a,b;
        cin>>a>>b;
        g[a].pb(b);
        g[b].pb(a);
    }

    dfs(1,-1);
    
    cout<<pos<<‘ ‘<<ans<<endl;
    //system("pause");
    return 0;
}

NC15033 小G有一个大树

原文:https://www.cnblogs.com/fxh0707/p/14634277.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!