Question link:
Http://uva.onlinejudge.org/index.php? Option = com_onlinejudge & Itemid = 8 & category = 460 & page = show_problem & problem = 4076
I have done a one-dimensional problem before. This problem is only two-dimensional, and other methods are the same. HDU 1506 largest rectangle in a Histogram
Code 1:
#include<cstdio>#include<cstring>#include<stack>using std::stack;const int MAXN = 1010;char str[MAXN*3];int sum[MAXN][MAXN];int left[MAXN], right[MAXN];int n, m;inline void input(){ scanf("%d%d%*c", &n, &m); for(int i=1; i<=n; ++i){ for(int j=1; j<=m; ++j){ char ch = getchar(); while(ch!='F' && ch!='R') ch=getchar(); sum[i][j] = ch=='R'?0:1; if(sum[i][j]) sum[i][j] += sum[i-1][j]; } } }inline void solve(){ input(); int ans = 0; for(int i=1; i<=n; ++i){ sum[i][0] = sum[i][m+1] = -1; for(int j=1; j<=m; ++j) left[j]=right[j]=j; for(int j=1; j<=m; ++j){ while(sum[i][j] <= sum[i][left[j]-1]) left[j] = left[left[j]-1]; } for(int j=m; j>=1; --j){ while(sum[i][j] <= sum[i][right[j]+1]) right[j] = right[right[j]+1]; int tmp = (right[j]-left[j]+1)*sum[i][j]; if(tmp > ans) ans=tmp; } } printf("%d\n", ans*3);}int main(){ int nCase; scanf("%d", &nCase); while(nCase--){ solve(); } return 0;}
Code 2 (stack scan ):
#include<cstdio>#include<cstring>#include<stack>using std::stack;const int MAXN = 1010;char str[MAXN*3];int sum[MAXN][MAXN];int n, m;inline void input(){ scanf("%d%d%*c", &n, &m); memset(sum, 0, sizeof(sum)); for(int i=1; i<=n; ++i){ for(int j=1; j<=m; ++j){ char ch = getchar(); while(ch!='F' && ch!='R') ch=getchar(); sum[i][j] = ch=='R'?0:1; if(sum[i][j]) sum[i][j] += sum[i-1][j]; } } }inline void solve(){ input(); int ans = 0; for(int i=1; i<=n; ++i){ sum[i][0] = sum[i][m+1] = -1; stack<int>q; for(int j=1; j<=m+1; ++j){ if(q.empty() || sum[i][j]>sum[i][q.top()]){ q.push(j); } else if(sum[i][j] < sum[i][q.top()]){ int pos; while(!q.empty() && sum[i][q.top()]>sum[i][j]){ int tmp = (j-q.top())*sum[i][q.top()]; if(tmp > ans) ans = tmp; pos = q.top(); q.pop(); } q.push(pos); sum[i][pos] = sum[i][j]; } } } printf("%d\n", ans*3);}int main(){ int nCase; scanf("%d", &nCase); while(nCase--){ solve(); } return 0;}