[POJ1655]Balancing Act

Problem Description

Consider a tree T with N (1 <= N <= 20,000) nodes numbered 1…N. Deleting any node from the tree yields a forest: a collection of one or more trees. Define the balance of a node to be the size of the largest tree in the forest T created by deleting that node from T.
For example, consider the tree:

Deleting node 4 yields two trees whose member nodes are {5} and {1,2,3,6,7}. The larger of these two trees has five nodes, thus the balance of node 4 is five. Deleting node 1 yields a forest of three trees of equal size: {2,6}, {3,7}, and {4,5}. Each of these trees has two nodes, so the balance of node 1 is two.

For each input tree, calculate the node that has the minimum balance. If multiple nodes have equal balance, output the one with the lowest number.
Input

The first line of input contains a single integer t (1 <= t <= 20), the number of test cases. The first line of each test case contains an integer N (1 <= N <= 20,000), the number of congruence. The next N-1 lines each contains two space-separated node numbers that are the endpoints of an edge in the tree. No edge will be listed twice, and all edges will be listed.

Output

For each test case, print a line containing two integers, the number of the node with minimum balance and the balance of that node.

Sample Input

1
7
2 6
1 2
1 4
4 5
3 7
3 1

Sample Output

1 2

My Problem Report

一道简单的树形DP,建图时注意建双向图,不要想当然地去建单向图。另外这道题可以不用记忆化,直接返回就行。

My Source Code

//  Created by Chlerry in 2015.
//  Copyright (c) 2015 Chlerry. All rights reserved.
//

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;
#define Size 20010
#define ll long long
#define mk make_pair
#define pb push_back
#define mem(array, x) memset(array,x,sizeof(array))
typedef pair<int,int> P;

int s,n,u,v,ans,ansn;
vector<int> a[Size];
bool visit[Size];

int DFS(int x)
{
    visit[x]=1;
    int t,sum=0,maxn=0;
    for(int i=0;iif(visit[a[x][i]]) continue;
        t=DFS(a[x][i]);
        sum+=t;
        maxn=max(maxn,t);
    }
    maxn=max(maxn,n-sum-1);
    if(maxnelse if(maxn==ans && xreturn sum+1;
}
int main()
{
    // std::cin.sync_with_stdio(false); 
    freopen("in.txt","r",stdin);
    int T;cin>>T;
while(T--)
{
    for(int i=0;i0);
    s=ans=ansn=INT_MAX;

    cin>>n;
    for(int i=1;icin>>u>>v;
        a[u].pb(v);
        a[v].pb(u);
    }
    DFS(1);
    cout<' '<return 0;
}


你可能感兴趣的:(---,Dynamic,Programming,---,Tree-DP)