首页 > 代码库 > Codeforces 509F Progress Monitoring 给定dfs序求树的同构数 区间dp

Codeforces 509F Progress Monitoring 给定dfs序求树的同构数 区间dp

题目链接:点击打开链接

==说同构数有点不对。。反正就是这个意思,对于某个点的所有儿子,先访问标号小的,再访问标号大的。

dp[l][r]表示 区间[l,r] 构成一棵树的方法数。

对于一个区间[l, r] 构成一棵树,则点l一定是根,然后枚举2个区间相乘即可

dp[l][r] = dp[l+1][i] * dp[i+1][r] ( i = [l+1, r] )

当然 a[i+1] > a[l+1] ,这样才会满足题目中的暴力代码。

import java.io.PrintWriter;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Scanner;
import java.util.Stack;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.Queue;

public class Main {
	int n;
	int[] a = new int[N];
	long[][] dp = new long[N][N];
	long dfs(int l, int r){
		if(dp[l][r] != -1)return dp[l][r];
		if(l >= r)return dp[l][r] = 1;
		long ans = 0;
		for(int i = l+1; i <= r; i++)
			if(i == r || a[i + 1] > a[l + 1])
				ans = (dfs(l+1, i) * dfs(i, r)+ans)%mod;	
		return dp[l][r] = ans;
	}
	void work() {
		while(cin.hasNext()){
			n = cin.nextInt(); for(int i = 1; i <= n; i++)a[i] = cin.nextInt();
			for(int i = 1; i <= n; i++){
				for(int j = i; j <= n; j++)dp[i][j] = -1;
			}
			System.out.println(dfs(1, n));
		}
	}

	Main() {
		cin = new Scanner(System.in);
		out = new PrintWriter(System.out);
	}

	public static void main(String[] args) {
		Main e = new Main();
		e.work();
		out.close(); 
	}

	public Scanner cin;
	public static PrintWriter out;
	static int N = 505;
	static int mod = 1000000007 ;
}



Codeforces 509F Progress Monitoring 给定dfs序求树的同构数 区间dp