cf23E 树形dp

来源:互联网 发布:美图字体软件 编辑:程序博客网 时间:2024/05/16 06:36

http://codeforces.com/problemset/problem/23/E

E. Tree
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

Recently Bob invented a new game with a tree (we should remind you, that a tree is a connected graph without cycles): he deletes any (possibly, zero) amount of edges of the tree, and counts the product of sizes of the connected components left after the deletion. Your task is to find out the maximum number that Bob can get in his new game for a given tree.

Input

The first input line contains integer number n (1 ≤ n ≤ 700) — amount of vertices in the tree. The following n - 1 lines contain the description of the edges. Each line contains the pair of vertices' indexes, joined by an edge, aibi (1 ≤ ai, bi ≤ n). It's guaranteed that the graph described in the input is a tree.

Output

Output the only number — the maximum product of sizes of the connected components, that Bob can get after deleting some of the tree's edges.

Sample test(s)
input
51 22 33 44 5
output
6
input
81 21 32 42 53 63 76 8
output
18
input
31 21 3
output
3
/** * cf23E树形dp * dp[u][j]表示以u为根节点含有j个节点的树切分乘积最大的情况。背包的思想:dp[u][a+b]=max(dp[u][a+b],dp[v][a]*dp[u][b]),{b:sum[a]-sum[b]} * */import java.util.*;import java.math.*;public class Main{static final int maxn=720;static BigInteger dp[][]=new BigInteger[maxn][maxn];static int va[][]=new int[maxn][maxn];static int n,sum[]=new int[maxn];static void dfs(int u,int pre){sum[u]=1;for(int i=0;i<=n;i++){dp[u][i]=BigInteger.valueOf(1);}for(int i=1;i<=va[u][0];i++){int v=va[u][i];if(v==pre)continue;dfs(v,u);sum[u]+=sum[v];for(int a=sum[u]-sum[v];a>=0;a--){for(int b=sum[v];b>=0;b--){dp[u][a+b]=dp[u][a+b].max(dp[u][a].multiply(dp[v][b]));}}}for(int i=1;i<=sum[u];i++){dp[u][0]=dp[u][0].max(dp[u][i].multiply(BigInteger.valueOf(i)));}}public static void main(String args[]){Scanner cin=new Scanner(System.in);n=cin.nextInt();for(int i=1;i<=n;i++){va[i][0]=0;for(int j=0;j<=n;j++){dp[i][j]=BigInteger.valueOf(1);}}for(int i=0;i<n-1;i++){int u=cin.nextInt();int v=cin.nextInt();va[u][++va[u][0]]=v;va[v][++va[v][0]]=u;}dfs(1,-1);System.out.println(dp[1][0]);}}


0 0
原创粉丝点击