原地去世
不知道这题坑了我好久,我真的好蠢啊!!!
首先我们很容易得出:正方形是最优的。那么,愚蠢的我灵光一现(大祸临头 ),想到:是不是尽量二分最优啊?答案是不是的!
看看这组数据:
4
。。。。
。。。#
。# # #
。# # #
如果二分,答案会是4,然而,正解是3。所以,其实我们要做的,是枚举!(当然,我们要用记忆化)
#include<cstdio>
#include<iostream>
using namespace std;
const int N = 52;
int n, dp[N][N][N][N], pre[N][N];
bool G[N][N];
int cal(int x, int y, const int tx, const int ty) {
x --;
y --;
return pre[tx][ty] + pre[x][y] - pre[tx][y] - pre[x][ty];
}
int dfs(const int x, const int y, const int tx, const int ty) {
if(dp[x][y][tx][ty])
return dp[x][y][tx][ty];
dp[x][y][tx][ty] = max(tx - x, ty - y) + 1;
int res = cal(x, y, tx, ty);
if(res == (tx - x + 1) * (ty - y + 1))
return dp[x][y][tx][ty];
if(res == 0)
return dp[x][y][tx][ty] = 0;
for(int i = x; i < tx; i ++)
dp[x][y][tx][ty] = min(dp[x][y][tx][ty], dfs(x, y, i, ty) + dfs(i + 1, y, tx, ty));
for(int i = y; i < ty; i ++)
dp[x][y][tx][ty] = min(dp[x][y][tx][ty], dfs(x, y, tx, i) + dfs(x, i + 1, tx, ty));
return dp[x][y][tx][ty];
}
int main() {
char t;
scanf("%d", &n);
for(int i = 1; i <= n; i ++) {
scanf("\n");
for(int j = 1; j <= n; j ++) {
scanf("%c", &t);
if(t == '#')
G[i][j] = 1;
pre[i][j] = pre[i][j - 1] + pre[i - 1][j] - pre[i - 1][j - 1] + G[i][j];
}
}
printf("%d\n", dfs(1, 1, n, n));
return 0;
}
另外,前缀和是用于特判情况的,不可删去。
希望大家指出错误,让我们一起努力!!!