原題:
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
累加求和後
00111110222'2'1330020411305
現在計算帶引號的那個2左邊有一個2滿足,右邊第一個是1,比2小,沒有辦法形成矩形。所以2的值的寬度就是2,再乘以高度,也就是本身的值2,結果是4。
計算每一個格子即可,求最大值即可,時間複雜度O(n^3)
此題可以最佳化~ 但是忘了怎麼弄了-_-