首页 > 代码库 > [luoguP1854] 花店橱窗布置(DP)

[luoguP1854] 花店橱窗布置(DP)

传送门

 

f[i][j] 表示前 i 盆花,放到前 j 个花盆中的最优解

pre[i][j] 记录前驱

代码

#include <cstdio>#include <cstring>#include <iostream>#define N 1001#define max(x, y) ((x) > (y) ? (x) : (y))int n, m, t;int a[N][N], f[N][N], pre[N][N], s[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;}int main(){	int i, j, k;	n = read();	m = read();	for(i = 1; i <= n; i++)		for(j = 1; j <= m; j++)			a[i][j] = read();	for(i = 1; i <= n; i++)		for(j = i; j <= m; j++)		{			f[i][j] = -1e9;			for(k = i; k <= j; k++)				if(f[i][j] < f[i - 1][k - 1] + a[i][k])				{					f[i][j] = f[i - 1][k - 1] + a[i][k];					pre[i][j] = k - 1;				}		}	k = m;	for(i = n; i; i--)	{		s[++t] = pre[i][k] + 1;		k = pre[i][k];	}	printf("%d\n", f[n][m]);	for(i = t; i; i--) printf("%d ", s[i]);	return 0;}

  

[luoguP1854] 花店橱窗布置(DP)