Luogu P1191 矩形【题解】

题目描述

给出一个 n × n n \times n 的矩阵,矩阵中,有些格子被染成白色,有些格子被染成黑色,现要求矩阵中白色矩形的数量。

输入输出格式

输入格式:

第一行,一个整数 n n ,表示矩形的大小。

接下来 n n 行,每行 n n 个字符,这些字符为“ W W ”或“ B B ”。其中“ W W ”表示白格,“ B B ”表示黑格。

输出格式:

一个正整数,为白色矩形数量

输入输出样例

输入样例#1:

4
WWBW
BBWB
WBWW
WBWB

输出样例#1: 复制

15

说明

对于 30 % 30\% 的数据, n 50 n ≤ 50

对于 100 % 100\% 的数据, n 150 n ≤ 150


洛谷上这个题其实是可以 n 4 n^4 过的,直接枚举就行,这里讲一下 n 3 n^3 做法。

首先处理一下每行的高度,就是 h h 数组,然后循环判断连续个数,累加即可。

//参考_Atyou大神代码
#include<iostream>
#include<cstdio>
#include<ctype.h>
using namespace std;
inline int read(){
    int x=0,f=0;char ch=getchar();
    while(!isdigit(ch))f|=ch=='-',ch=getchar();
    while(isdigit(ch))x=x*10+(ch^48),ch=getchar();
    return f?-x:x;
}
char c[157][157];
int n,h[157],ans;
int main() {
	int n=read();
    for(int i=1;i<=n;i++)scanf("%s",c[i]+1);
    for(int i=1;i<=n;i++){
        for(int j=1;j<=n;j++)//扫一遍
            if(c[i][j]!='B')h[j]++;//判断每行连续的白色个数
            else h[j]=0;//因为只统计白色高度,所以如果遇到黑色就清零
        for(int j=1;j<=n;++j){
        	int high=h[j];  
            for(int k=j;k<=n;++k){
                if(!h[k])break;
                high=min(high,h[k]);//连续个数取min
                ans+=high;//矩形个数=连续个数
            }
        }
    }
    printf("%d\n",ans);
    return 0;
}
又:考试考到这个题的强化版, n 2000 n≤2000 ,留坑待填。

回来填坑:

用单调栈维护每个区间内的最大值,出栈时

写一份考试题的代码:
#include<iostream>
#include<cstdio>
#include<ctype.h>
using namespace std;
inline int read(){
    int x=0,f=0;char ch=getchar();
    while(!isdigit(ch))f|=ch=='-',ch=getchar();
    while(isdigit(ch))x=x*10+(ch^48),ch=getchar();
    return f?-x:x;
}
char c[2007][2007];
int up[2007][2007],L[2007],R[2007];
int s[2007];
long long ans;
int main() {
    int n=read(),m=read();
    for(int i=1;i<=n;++i)scanf("%s",c[i]+1);
    for(int i=1;i<=n;++i)for(int j=1;j<=m;++j)
        if(c[i][j]=='.')up[i][j]=up[i-1][j]+1;
    for(int i=1;i<=n;i++){
        int top=0;s[0]=0;
        for(int j=1;j<=m;j++){
            while(top && up[i][j]<=up[i][s[top]])--top;
            L[j]=s[top]+1;s[++top]=j;
        }
        top=0;s[0]=m+1;
        for(int j=m;j>=1;--j){
            while(top && up[i][j]<up[i][s[top]])--top;
            R[j]=top?s[top]-1:m;s[++top]=j;
        }
        for(int j=1;j<=m;++j){
            long long l=j-L[j]+1,r=R[j]-j+1,h=up[i][j];  
            ans+=h*(h+1)/2*(l+r)*l*r/2;
        }
    }
    printf("%lld\n",ans);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_44023181/article/details/85111281
今日推荐