码迷,mamicode.com
首页 > 其他好文 > 详细

[luoguP1040] 加分二叉树(DP)

时间:2017-07-02 16:20:25      阅读:118      评论:0      收藏:0      [点我收藏+]

标签:highlight   iostream   efi   print   class   lin   ==   tchar   i++   

传送门

 

区间DP水题

 

代码

#include <cstdio>
#include <iostream>
#define N 41
#define max(x, y) ((x) > (y) ? (x) : (y))

int n;
int a[N], f[N][N], pre[N][N];

inline int read()
{
	int x = 0, f = 1;
	char ch = getchar();
	for(; !isdigit(ch); ch = getchar()) if(ch == ‘-‘) f = -1;
	for(; isdigit(ch); ch = getchar()) x = (x << 1) + (x << 3) + ch - ‘0‘;
	return x * f;
}

inline void solve(int l, int r)
{
	printf("%d ", pre[l][r]);
	if(l <= pre[l][r] - 1) solve(l, pre[l][r] - 1);
	if(pre[l][r] + 1 <= r) solve(pre[l][r] + 1, r);
}

int main()
{
	int i, j, k;
	n = read();
	for(i = 1; i <= n; i++) f[i][i] = read(), pre[i][i] = i;
	for(i = n; i >= 1; i--)
		for(j = i + 1; j <= n; j++)
		{
			if(f[i][i] + f[i + 1][j] > f[i][j])
				f[i][j] = f[i][i] + f[i + 1][j], pre[i][j] = i;
			for(k = i + 1; k < j; k++)
				if(f[i][k - 1] * f[k + 1][j] + f[k][k] > f[i][j])
					f[i][j] = f[i][k - 1] * f[k + 1][j] + f[k][k], pre[i][j] = k;
			if(f[j][j] + f[i][j - 1] > f[i][j])
				f[i][j] = f[j][j] + f[i][j - 1], pre[i][j] = j;
		}
	printf("%d\n", f[1][n]);
	solve(1, n);
	return 0;
}

  

[luoguP1040] 加分二叉树(DP)

标签:highlight   iostream   efi   print   class   lin   ==   tchar   i++   

原文地址:http://www.cnblogs.com/zhenghaotian/p/7106046.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!