cf23E 树形dp

25 篇文章 0 订阅

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
5
1 2
2 3
3 4
4 5
output
6
input
8
1 2
1 3
2 4
2 5
3 6
3 7
6 8
output
18
input
3
1 2
1 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
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值