POJ 1655 Balancing Act

树型DP。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#define maxv 50050
#define maxe 100050
#define inf 1000000007
using namespace std;
int t,n,x,y,nume=0,g[maxv],size[maxv];
struct edge
{
    int v,nxt;
}e[maxe];
struct pnt
{
    int id,bal;
}p[maxv];
bool cmp(pnt x,pnt y)
{
    if (x.bal!=y.bal)
        return x.bal<y.bal;
    return x.id<y.id;
}
void addedge(int u,int v)
{
    e[++nume].v=v;
    e[nume].nxt=g[u];
    g[u]=nume;
}
void dfs(int x,int fath)
{
    size[x]=1;int ret=0;
    for (int i=g[x];i;i=e[i].nxt)
    {
        int v=e[i].v;
        if (v!=fath)
        {
            dfs(v,x);
            ret=max(ret,size[v]);
            size[x]+=size[v];
        }
    }
    ret=max(ret,n-size[x]);
    p[x].id=x;p[x].bal=ret;
}
void work()
{
    nume=0;memset(g,0,sizeof(g));
    scanf("%d",&n);
    for (int i=1;i<=n-1;i++)
    {
        scanf("%d%d",&x,&y);
        addedge(x,y);
        addedge(y,x);
    }
    dfs(1,1);
    sort(p+1,p+n+1,cmp);
    printf("%d %d
",p[1].id,p[1].bal);
}
int main()
{
    scanf("%d",&t);
    for (int i=1;i<=t;i++)
        work();
    return 0;
}
原文地址:https://www.cnblogs.com/ziliuziliu/p/5660564.html