如果暴力的话,时间复杂度是\(rcC(n, n/2)^2\),主要考察搜索枚举行和列,并没有用到DP的思想。
考虑优化的话,发现枚举行或列中至少需要一步,因为这个题只能预处理优化,如果都不枚举,就相当于盲人摸象,无法预处理来优化。
因此要搜索枚举行或列,然后预处理并在列或行上跑DP,这样就可以少些枚举时间,多些转移时间。
这里我用了枚举行,预处理关于列上的数组,并在列上跑DP。
预处理和DP数组如下:
\(dp[i][j]\)表示前\(i\)列,已用\(j\)列得到的最小价值。
\(ver[i]\)表示对于\(i\)列的上下绝对值差的和,\(del[i][j]\)表示\(i\)列和\(j\)列左右差的和
状态转移方程:
$dp[i][j] = min(dp[i][j],dp[i-k][j-1]+ver[i]+del[i-k][i]); $
50pts:
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;
int n, m, r, c, dp1[109], dp2[109], a[19][19];
int ans = 0x7fffffff;
void Dp()
{
int now = 0;
for (int i = 1; i <= r; i++)
for (int j = 2; j <= c; j++)
now += abs(a[dp1[i]][dp2[j]] - a[dp1[i]][dp2[j-1]]);
for (int i = 2; i <= r; i++)
for (int j = 1; j <= c; j++)
now += abs(a[dp1[i]][dp2[j]] - a[dp1[i-1]][dp2[j]]);
ans = min(ans, now);
}
void dfs(int x, int y, int nr, int nc)
{
if (nc == c + 1)
return Dp();
if ((x > n && nr != r + 1) || (y > m && nc != c + 1)) return;
if (nr == r + 1)
{//先枚举行,再枚举列
for (int i = y; i <= m; i++)
{
dp2[nc] = i;
dfs(x, i + 1, nr, nc + 1);
}
return;
}
else
for (int i = x; i <= n; i++)
{
dp1[nr] = i;
dfs(i + 1, y, nr + 1, nc);
}
}
int main()
{
scanf("%d%d%d%d", &n, &m, &r, &c);
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++)
scanf("%d", &a[i][j]);
dfs(1, 1, 1, 1);
printf("%d\n", ans);
return 0;
}
100pts:
#include <algorithm>
#include <iostream>
#include <cstring>
#include <cstdio>
#include <cmath>
using namespace std;
int n, m, r, c, ans = 2147483647;
int a[19][19], hang[19], dp[19][19];
int ver[19], del[19][19];//ver[i]表示对于i列的上下绝对值差的和,del[i][j]表示i列和j列左右差的和
inline void Dp()
{
memset(dp, 123, sizeof(dp));
memset(ver, 0, sizeof(ver));
memset(del, 0, sizeof(del));
for (int i = 1; i <= m; i++)//枚举每一列i
for (int j = 2; j <= r; j++)
ver[i] += abs(a[hang[j]][i] - a[hang[j - 1]][i]) ;
for (int i = 1; i <= m; i++)
for (int k = i + 1; k <= m; k++)
for (int j = 1; j <= r; j++)
del[i][k] += abs(a[hang[j]][k] - a[hang[j]][i]);
for (int i = 1; i <= m; i++)
dp[i][1] = ver[i];
for (int i = 1; i <= m; i++)
for (int j = 1; j <= c; j++)
for (int k = 1; k < i && i - k >= j - 1; k++)
dp[i][j] = min(dp[i][j], dp[i - k][j - 1] + ver[i] + del[i - k][i]);
for (int i = c; i <= m; i++)//从c行后取最小值
ans = min(ans, dp[i][c]);
}
void dfs(int now, int pos)
{
if (now == r + 1)
{
Dp();
return;
}
if (pos == n + 1)
return;
for (int i = pos; i <= n; i++)
hang[now] = i, dfs(now + 1, i + 1);
}
int main()
{
scanf("%d%d%d%d", &n, &m, &r, &c);
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++)
scanf("%d", &a[i][j]);
dfs(1, 1);
printf("%d", ans);
}