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