Codeforces Round #576 (Div. 2)F. Rectangle Painting 1【DP】

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;
}

 

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值