跳到正文

题解

题解 P1395 【会议】

HHCY约 2 分钟
原文
文章信息与版本

文章信息

发布
2017年12月26日
收录
2026年6月29日
更新
2026年11月13日
篇幅
约 2 分钟
获赞
86
题目
P1395

版本

  1. v1当前

/*复杂度O(n)

这题思路就是建一棵树

我以1作为根

算出把地点定在1的距离和

用f[1]表示

从1往下遍历这棵树

假设x是当前遍历到的点

y是上个点(x的父亲)

则f[x]=f[y]-(hason[x]+1)+(n-hason[x]-1);

hason[i]表示以点i为根的子树的节点个数

这样就很容易得到答案

主要用到搜索

*/

C++
#include<iostream>
#include<cmath>
#include<cstdio>
#include<algorithm>
using namespace std;
const int p=50001;
int n,hason[p],f[p],yy=1;
int u,v;
int tot,la[p*2],to[p*2],h[p];
void hsb(int x,int y)
{
    to[++tot]=y,
    la[tot]=h[x],
    h[x]=tot;
}
int hsc(int x,int y)
{
    for(int i=h[x];i;i=la[i])
    if(to[i]!=y)
    hason[x]+=1+hsc(to[i],x);
    return hason[x];
}
void hsa(int x,int y)
{
    f[x]=f[y]-(hason[x]+1)+(n-hason[x]-1);
    for(int i=h[x];i;i=la[i])
    if(to[i]!=y)hsa(to[i],x);
}
void hsd(int x,int y,int z)
{
    f[1]+=z;
    for(int i=h[x];i;i=la[i])
    if(to[i]!=y)
    hsd(to[i],x,z+1);
}
int main()
{
    scanf("%d",&n);
    for(int i=1;i<n;i++)
    {
        scanf("%d%d",&u,&v);
        hsb(u,v),hsb(v,u);
    }
    hsc(1,0);
    for(int i=h[1];i;i=la[i])
    hsd(to[i],1,1);
    for(int i=h[1];i;i=la[i])
    hsa(to[i],1);
    for(int i=2;i<=n;i++)
    if(f[i]<f[yy])yy=i;
    printf("%d %d\n",yy,f[yy]);
    return 0;
}
原文
存档评论136 条抓取于