F. Rectangle Painting 1
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output
There is a square grid of size n×nn×n. Some cells are colored in black, all others are colored in white. In one operation you can select some rectangle and color all its cells in white. It costs max(h,w)max(h,w) to color a rectangle of size h×wh×w. You are to make all cells white for minimum total cost.
Input
The first line contains a single integer nn (1≤n≤501≤n≤50) — the size of the square grid.
Each of the next nn lines contains a string of length nn, consisting of characters '.' and '#'. The jj-th character of the ii-th line is '#' if the cell with coordinates (i,j)(i,j) is black, otherwise it is white.
Output
Print a single integer — the minimum total cost to paint all cells in white.
Examples
input
Copy
3 ### #.# ###
output
Copy
3
input
Copy
3 ... ... ...
output
Copy
0
input
Copy
4 #... .... .... #...
output
Copy
2
input
Copy
5 #...# .#.#. ..... .#... #....
output
Copy
5
Note
The examples and some of optimal solutions are shown on the pictures below.
分析:用dp[sx][sy][ex][ey]表示这个矩形的最小花费,那么这个状态就由两个子矩阵转移而来。
#include "bits/stdc++.h"
using namespace std;
int dp[54][54][54][54];
char mp[54][54];
int dfs(int sx,int sy,int ex,int ey){
if(dp[sx][sy][ex][ey]!=-1)return dp[sx][sy][ex][ey];
int res = max(ex - sx + 1,ey - sy + 1);
if(sx!=ex)
for (int i = sx; i < ex; ++i) {
res = min(res, dfs(sx,sy,i,ey) + dfs(i+1,sy,ex,ey));
}
if(sy!=ey)
for (int i = sy; i < ey; ++i) {
res = min(res, dfs(sx,sy,ex,i) + dfs(sx,i+1,ex,ey));
}
return dp[sx][sy][ex][ey] = res;
}
int main(){
int n;
cin>>n;
for (int i = 1; i <= n; ++i) {
scanf("%s",mp[i]+1);
}
memset(dp,-1, sizeof(dp));
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= n; ++j) {
if(mp[i][j]=='#')dp[i][j][i][j]=1;
else dp[i][j][i][j]=0;
}
}
cout<<dfs(1,1,n,n)<<endl;
}