多叉树计数,Exploring Pyramids, NEERC 2005, LA 3516
来源:互联网 发布:三菱系统手动编程实例 编辑:程序博客网 时间:2024/06/10 02:23
给一颗多叉树,每个结点的子结点都有从左到右的顺序,从根结点开始,每次尽量选择靠左的分支走,走不通就回溯,把遇到的字母记录下来,可以得到一个序列。 给定一个序列,问有多少树和他对应?
令 S 表示给定序列,d[i][j] 表示字符区间 [i,j] 对应的不同的树的数目,则有如下边界条件:
如果 i == j 则 d[i][j] = 1
如果 S[i] != S[j] 则 d[i][j] = 0,因为从根出发一定回溯到根,区间的首末字符必须一样才构成一颗树
再考虑递推表达式,一颗树如果去掉其最左分支,仍然是一颗树,所以树的数目等于最左分支的数目乘以剩余部分树的数目;如果序列首字符是 S[i] == A ,那么区间[i+1, j] 中出现的每个字符 A 都可以作为最左分支与剩余部分的边界;所以 d[i][j] = sum { d[i+1][k-1] * d[k][j] , i+2<=k<=j && S[k] == A }
public class ExplorringPyramid {// d[i][j] 表示从区间[i,j]之间的字母组成的不同的树的数目// d[i][j] = 0 if A[i] != A[j]// d[i][j] = 1 if i == j// d[i][j] = sum { d[i+1][k-1]*d[k][j] | i+1<k<=j }public static int solve(String str) {int n = str.length();int[][] d = new int[n][n];for ( int i=0; i<n; i++ )for ( int j=0; j<n; j++ )d[i][j] = -1;return dp(str, d, 0, n-1);}private static int dp(String str, int[][] d, int i, int j) {if ( d[i][j] >= 0)return d[i][j];int res = 0;if ( i == j ) {res = 1;} else if ( str.charAt(i) != str.charAt(j) ) {res = 0;} else {for ( int k=i+2; k<=j; k++ ) {res += dp(str,d,i+1,k-1)*dp(str,d,k,j);}}d[i][j] = res;return res;}// 测试public static void main(String[] args) {String[] strs = { "ABABABA" };for ( String str : strs ) {System.out.printf("%s - %d", str, solve(str));}}}
- 多叉树计数,Exploring Pyramids, NEERC 2005, LA 3516
- LA 3516 Exploring Pyramids 多叉树遍历
- UVa 1362(LA 3516) Exploring Pyramids
- LA 3516 Exploring Pyramids 记忆化搜索
- LA 3516 Exploring Pyramids (递推)
- LA 3516 - Exploring Pyramids (记忆化搜索dp)
- UVaLive ( LA ) 3516 - Exploring Pyramids (DP 递推)
- UVALive 3516 Exploring Pyramids 区间dp+计数原理
- UVALive - 3516 Exploring Pyramids
- UVALive 3516Exploring Pyramids
- UVALive 3516 Exploring Pyramids
- uva live 3516 - Exploring Pyramids
- UVA-3516 Exploring Pyramids (DP)
- POJ 2795 (LA 3516) Exploring Pyramids 解题报告(递推)
- UVA 1362 - Exploring Pyramids(计数问题+区间DP)
- uva live 3516 Exploring Pyramids 区间DP
- UVAlive - 3516 —— Exploring Pyramids
- UVa 1362 Exploring Pyramids (多叉树遍历&DP)
- 如何获取ResultSet的行数和列数
- 序列123...N,N介于3和9之间,在其中加入+-或者空格,使其和为0
- 第二章 图形系统的基本功能和组成
- C语言文件操作---fputs
- Struts2+Spring+iBatis+Jquery的框架搭建一
- 多叉树计数,Exploring Pyramids, NEERC 2005, LA 3516
- open-iscsi源码分析 -- 流程详细分析
- wiki_AutoHotkey
- How to Make an Exe File
- 结构体与位结构体
- NetBeans学习笔记3
- open-iscsi源码分析 -- 进程通信
- open-iscsi源码分析 -- list-head分析
- vector c++详细用法