原题:
Let A be an N × N matrix of zeros and ones. A submatrix S of A is any group of contiguous entries that forms a square or a rectangle. Write a program that determines the number of elements of the largest submatrix of ones in A. Largest here is measured by area.
Input
The input begins with a single positive integer on a line by itself indicating the number
of the cases following, each of them as described below. This line is followed by a blank line, and there is also a blank line between two consecutive inputs.
The matrix is given line by line. Each line consists of 0’s and 1’s. The order of the matrix is also the number of lines input and 1 < N ≤ 25.
Output
For each test case, the output must follow the description below. The outputs of two
consecutive cases will be separated by a blank line.
The output is the number of elements of the largest submatrix found.
Sample Input
1
10111000
00010100
00111000
00111010
00111111
01011110
01011110
00011110
Sample Output
16
中文:
找出最大1矩阵的和、
#include<bits/stdc++.h>
using namespace std;
int dp[30][30];
int sum[30][30];
char tmps[30][30];
int main()
{
ios::sync_with_stdio(false);
int t;
cin>>t;
cin.ignore();
for(int k=1;k<=t;k++)
{
memset(dp,0,sizeof(dp));
cin>>tmps[0];
int row=strlen(tmps[0]);
int col=row;
for(int i=1;i<row;i++)
cin>>tmps[i];
for(int i=1;i<=row;i++)
{
for(int j=1;j<=col;j++)
sum[i][j]=tmps[i-1][j-1]-'0';
}
for(int i=1;i<row;i++)
{
for(int j=1;j<=col;j++)
{
if(sum[i+1][j]==1)
{
sum[i+1][j]=sum[i][j]+1;
}
}
}
int ans=0;
for(int i=1;i<=row;i++)
{
for(int j=1;j<=col;j++)
{
int width=1;
for(int left=j-1;;left--)
{
if(j==0)
break;
if(sum[i][left]<sum[i][j])
break;
else
width++;
}
for(int right=j+1;;right++)
{
if(right==col+1)
break;
if(sum[i][right]<sum[i][j])
break;
else
width++;
}
dp[i][j]=sum[i][j]*width;
ans=max(dp[i][j],ans);
}
}
cout<<ans<<endl;
if(k<t)
cout<<endl;
}
return 0;
}
思路:
在杭电上曾经做过类似的题目,首先逐行累加每个1。意义是得到连续1的高度
例如有矩阵
0110
0010
0110
1110
逐行累加之后就是
0110
0020
0130
1240
此时每个单元格子表示1的高度是多少,接下来枚举宽度
计算每个格子左侧和右侧连续且高度大于等于当前格子的格子数数是多少
例如有矩阵
00111
11011
11111
00101
11101
累加求和后
00111
11022
2'2'133
00204
11305
现在计算带引号的那个2左边有一个2满足,右边第一个是1,比2小,没有办法形成矩形。所以2的值的宽度就是2,再乘以高度,也就是本身的值2,结果是4。
计算每一个格子即可,求最大值即可,时间复杂度O(n^3)
此题可以优化~ 但是忘了怎么弄了-_-