首页 > 代码库 > [luoguP3146] [USACO16OPEN]248(区间DP)

[luoguP3146] [USACO16OPEN]248(区间DP)

传送门

 

f[i][j]表示区间 i-j 合并的最大值

转移:

若f[i][k] && f[k+1][j] && f[i][k] == f[k+1][j] --> f[i][j] = max(f[i][k]+1,f[i][j])

但要注意, 若f[i][k]!=f[k+1][j],那么无法进行转移

代码

#include <cstdio>#include <iostream>#define max(x, y) ((x) > (y) ? (x) : (y))int n, ans;int f[5001][5001];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;}int main(){	int i, j, k;	n = read();	for(i = 1; i <= n; i++) f[i][i] = read(), ans = max(ans, f[i][i]);	for(i = n - 1; i >= 1; i--)		for(j = i + 1; j <= n; j++)		{			for(k = i; k < j; k++)				if(f[i][k] && f[k + 1][j] && f[i][k] == f[k + 1][j])					f[i][j] = max(f[i][j], f[i][k] + 1);			ans = max(ans, f[i][j]);		}	printf("%d\n", ans);	return 0;} 

  

[luoguP3146] [USACO16OPEN]248(区间DP)