CodeForces509F Progress Monitoring

给出一颗树以下方程序遍历的dfs序

used[1 ... n] = {0, ..., 0};

procedure dfs(v):
    print v;
    used[v] = 1;
    for i = 1, 2, ..., n:
        if (a[v][i] == 1 and used[i] == 0):
            dfs(i);

dfs(1);

问可以得到此序列的树的个数

观察发现同一子树处在相邻区间,且子树的根为该区间第一个元素,定义dp[l][r]为区间[l,r]的方案,则:

\[dp[l][r]=\sum_{i\in[l,r],i!=r||b[i+1]>b[l]} dp[l+1][i]*dp[i+1][r] \]

#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;
const int mod = 1e9 + 7;
int n, b[505];
int f[505][505];
void ModAdd(int & x, int y) {
	x += y;
	if(x >= mod) x-= mod;
}
int DP(int l, int r) {
//	cerr << l << ' ' << r << endl;
	if(l >= r) return 1;
	int & res = f[l][r];
	if(res != -1) return res;
	res = 0;
	for(int i = l; i <= r; i++) {
		if(i != r && b[i + 1] <= b[l]) continue;
		ModAdd(res, (long long)DP(l + 1, i) * DP(i + 1, r) % mod);
	}
	return res;
}
int main() {
	scanf("%d", &n);
	for(int i = 1; i <= n; i++) scanf("%d", &b[i]);
	memset(f, -1, sizeof(f));
	printf("%d\n", DP(2, n));
	return 0;
}
posted @ 2018-05-20 19:22  LJZ_C  阅读(166)  评论(0编辑  收藏  举报