树的重心

拿掉重心后,最大的联通分量的点的个数最少。

using namespace std;

const int MAXE = 80010;
const int MAXP = 40010;

struct EDGE
{
    int v,next;
}edge[MAXE];
int head[MAXP];
int Top;

void Link(int u,int v)
{
    edge[Top].v = v;
    edge[Top].next = head[u];
    head[u] = Top++;
}

int PointNum[MAXP];
int MaxPointNum[MAXP];

int CalPointNum(int s,int pre)
{
    PointNum[s] = 1;

    for(int p = head[s];p != -1; p = edge[p].next)
    {
        if(edge[p].v != pre)
            PointNum[s] += CalPointNum(edge[p].v,s);
    }

    return PointNum[s];
}

void CalMaxPointNum(int s,int sum,int pre)
{
    MaxPointNum[s] = sum - PointNum[s];

    for(int p = head[s] ; p != -1; p = edge[p].next)
    {
        if(edge[p].v != pre)
        {
            MaxPointNum[s] = max(MaxPointNum[s],PointNum[edge[p].v]);
            CalMaxPointNum(edge[p].v,sum,s);
        }
    }

}

void SearchGC(int n)
{
    CalPointNum(1,-1);
    CalMaxPointNum(1,n,-1);

    int Min = n,anw = 1;

    for(int i = 1;i <= n; ++i)
        if(Min > MaxPointNum[i])
            Min = MaxPointNum[i],anw = i;

    printf("%d %d\n",anw,MaxPointNum[anw]);
}

你可能感兴趣的:(模板,图论)