标签:
| Time Limit: 1000MS | Memory Limit: 65536K | |
| Total Submissions: 11176 | Accepted: 4702 | 
Description

Input
Output
Sample Input
1 7 2 6 1 2 1 4 4 5 3 7 3 1
Sample Output
1 2
Source
#include <iostream>
#include <cstdio>
#include <cstring>
#include <stack>
#include <queue>
#include <map>
#include <set>
#include <vector>
#include <cmath>
#include <algorithm>
using namespace std;
const double eps = 1e-6;
const double pi = acos(-1.0);
const int INF = 0x3f3f3f3f;
const int MOD = 1000000007;
#define ll long long
#define CL(a,b) memset(a,b,sizeof(a))
#define MAXN 40010
struct node
{
    int v;
    node *next;
}tree[MAXN], *head[MAXN];
int n,pre,dp[MAXN];
int ans,num,tot;
void init()
{
    ans = INF;
    pre = 1;
    CL(dp, 0);
    CL(head, NULL);
}
void add(int x, int y)
{
    tree[pre].v = y;
    tree[pre].next = head[x]; head[x] = &tree[pre++];
    tree[pre].v = x;
    tree[pre].next = head[y]; head[y] = &tree[pre++];
}
void dfs(int son, int father)
{
    node *p = head[son];
    dp[son] = 1;
    while(p != NULL)
    {
        if(p->v != father)
        {
            dfs(p->v, son);
            dp[son] += dp[p->v];
        }
        p = p->next;
    }
}
void dp_tree(int son, int father)
{
    int maxx = 0;
    node *p = head[son];
    while(p != NULL)
    {
        if(p->v != father)
        {
            dp_tree(p->v, son);
            maxx = max(maxx, dp[p->v]);
        }
        p = p->next;
    }
    maxx = max(maxx, n-dp[son]);
    if(maxx < ans)//对比poj3107,也就改下这里,只把最小的保存下来就行了
    {
        ans = maxx;
        num = son;
    }
    else if(maxx == ans)
    {
        if(num > son) num = son;
    }
}
int main()
{
    int T,a,b;
    scanf("%d",&T);
    while(T--)
    {
        scanf("%d",&n);
        init();
        for(int i=1; i<n; i++)
        {
            scanf("%d%d",&a,&b);
            add(a, b);
        }
        dfs(1, 0);
        dp_tree(1, 0);
        printf("%d %d\n",num, ans);
    }
    return 0;
}
标签:
原文地址:http://blog.csdn.net/d_x_d/article/details/50068571