Codeforces Round #576 (Div. 2) F. Rectangle Painting 1(dfs搜矩形)

F. Rectangle Painting 1

传送门
There is a square grid of size n×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) to color a rectangle of size h×w. You are to make all cells white for minimum total cost.

Input
The first line contains a single integer n (1≤n≤50) — the size of the square grid.

Each of the next n lines contains a string of length n, consisting of characters ‘.’ and ‘#’. The j-th character of the i-th line is ‘#’ if the cell with coordinates (i,j) is black, otherwise it is white.

Output
Print a single integer — the minimum total cost to paint all cells in white.

在这里插入图片描述

题目大意:

有一个大小为n×n的方格。有些单元格是黑色的,其他单元格都是白色的。在一个操作中,您可以选择一些矩形,并将其所有单元格都涂成白色。为一个H×W大小的矩形上色的成本最高(H,W)。您要使所有单元格都为白色,以最低的总成本。

思路:

看了这篇大佬(mzdl)的题解才发现dfs和dp还可以这么巧妙的用。
用dfs爆搜遍历各种情况然后取最优。
想了好久没想到不开四维的方法,找别人的代码也没有,所以还是看四维的解法吧。

ac_code:

#include<bits/stdc++.h>
using namespace std;
const int maxn=55;

char mp[maxn][maxn];
int dp[maxn][maxn][maxn][maxn];

int dfs(int a,int b,int x,int y){
    if(a==x&&b==y)
        return (mp[x][y]=='#');
    if(dp[a][b][x][y]!=-1)
        return dp[a][b][x][y];
    dp[a][b][x][y]=max(x-a,y-b)+1; //加上消耗的值
    for(int i=a;i<x;i++)
        dp[a][b][x][y]=min(dp[a][b][x][y],dfs(a,b,i,y)+dfs(i+1,b,x,y));//判断哪种情况更优
    for(int i=b;i<y;i++)
        dp[a][b][x][y]=min(dp[a][b][x][y],dfs(a,b,x,i)+dfs(a,i+1,x,y));
    return dp[a][b][x][y];     
}

int main(){
    int N;
    scanf("%d",&N);
    for(int i=0;i<N;i++){
       scanf("%s",mp[i]);
    }
    memset(dp,-1,sizeof(dp));
    cout<<dfs(0,0,N-1,N-1)<<endl;
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值