思路同紫书,解法很巧妙,逐行求解,设置一个数组height记录当前扫到的某一行的某一个格子之后,对应这个列的高度,同时设置一个栈结构来进行记录。如果当前扫到的是‘#’,那么就将这一列对应的高度记为0,同时清空栈,如果扫到的为‘.’,那么就将这一行的高度加1,同时注意当前栈中是否为空,如果为空,那么就将这个数据压入栈中,如果不为空,那么就按照紫书上所讲的最优的情况(也就是周长最大的情况),不断地将数据出栈,最后测试,必要的时候将数据进栈,最后计算出对应周长的一般,同时计数加1。以上全部处理完之后输出最终的结果,具体实现见如下代码:
#include<iostream>
#include<vector>
#include<string>
#include<set>
#include<stack>
#include<queue>
#include<map>
#include<algorithm>
#include<cmath>
#include<iomanip>
#include<cstring>
#include<sstream>
#include<cstdio>
#include<deque>
#include<functional>
using namespace std;
const int maxn = 1000 + 10;
int height[maxn],ans[maxn*2];
string area[maxn];
typedef struct Rect{
int x, h;
Rect(int x1=0, int h1=0) :x(x1), h(h1){}
}Rect;
Rect st[maxn];
int main(){
int T;
cin >> T;
while (T--){
int n, m;
cin >> n >> m;
fill(ans, ans + n + m + 10, 0);
for (int i = 0; i < n; i++) cin >> area[i];
fill(height, height + m, 0);
for (int i = 0; i < n; i++){
int top = -1;
for (int j = 0; j < m; j++){
if (area[i][j] == '#'){
height[j] = 0;
top = -1;
}
else{
height[j]++;
Rect temp(j,height[j]);
if (top < 0){
st[++top] = temp;
}
else{
while (top >= 0 && temp.h<=st[top].h ){
temp.x = st[top--].x;
}
if (top<0 || temp.h - temp.x>st[top].h - st[top].x){
st[++top] = temp;
}
}
ans[j - st[top].x + 1 + st[top].h]++;
}
}
}
for (int i = 1; i <= n + m; i++){
if (ans[i]){
cout << ans[i] << " x " << i * 2 << endl;
}
}
}
return 0;
}