poj1964 City Game(单调栈)

题意

求F组成的最大矩阵。

题解

单调栈
这是poj2559的升级版。
思路是求出每个点上的最大F长度,相当于矩阵高。接着一行一行地做单调栈,求以每个点为左下角的最大F矩阵。

代码

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxl=1010;

int n,m;
int h[maxl][maxl];//h记录每个点上面最长的F 

int top,sta_h[maxl],sta_p[maxl];//建立以sta_h为主体的单调递增栈(sta_h[i]<sta_h[top])

char ch[5];
int main()
{
    int T;scanf("%d",&T);
    while(T--)
    {
        scanf("%d%d",&n,&m);
        for(int i=1;i<=n;i++)
        {
            for(int j=1;j<=m;j++)
            {
                scanf("%s",ch);
                if(ch[0]=='F') h[i][j]=h[i-1][j]+1;
                else h[i][j]=0;
            }
            h[i][m+1]=0;
        }
        
        int ans=0;
        for(int i=1;i<=n;i++)
        {
            top=0;int mx=0;
            for(int j=1;j<=m+1;j++)//以h[m+1]=0结束,避免了矩阵残留 
            {
                int mnp=j;
                while(top>0 && h[i][j]<=sta_h[top])
                {
                    mx=max(mx,(j-sta_p[top])*sta_h[top]);
                    mnp=min(mnp,sta_p[top]);
                    top--;
                }
                top++;sta_h[top]=h[i][j];sta_p[top]=mnp;
            }
            ans=max(ans,mx);
        }
        printf("%d\n",ans*3);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/A_Bright_CH/article/details/81630908
今日推荐