Accept: 137 Submit: 782
Time Limit: 3000 mSec
Problem Description
Input
On the first line a positive integer: the number of test cases, at most 100. After that per test case:
• One line with two integers n and m (1 ≤ n,m ≤ 1000): the dimensions of Per’s parcel.
• n lines, each with m characters. Each character is either ‘#’ or ‘.’. The j-th character on the i-th line is a ‘#’ if position (i,j) is a swamp, and ‘.’ if it is grass. The north-west corner of Per’s parcel has coordinates (1, 1), and the south-east corner has coordinates (n,m).
Output
Sample Input
6 5
..#.#
.#...
#..##
...#.
#....
#..#.
Sample Output
6 x 4
5 x 6
5 x 8
3 x 10
1 x 12
题解:很多类似的有障碍物的关于矩形的题都会用到单调栈,算是个小经验吧,以后再碰到这类题多往这边想想。预处理一个最高延伸高度的height数组是非常自然的,在处理每一列时,如果当前列高度大于栈顶元素的高度,只用分析当前列是否可能成为最优解,如果可能就压入栈中,否则继续遍历。如果当前列高度小于等于栈顶元素,那就需要弹栈了,直到栈顶元素高度小于当前列高度,这时判断是否时最优解时,用的不是当前列的列数,而是弹栈的最后一个元素的列数,这是因为要最大化h-c,相同的方法判断能否成为最优解,决定是否压入栈中即可。
#include <bits/stdc++.h> using namespace std; const int maxn = + ; int n, m;
int height[maxn], ans[maxn << ];
char gra[maxn][maxn]; struct Node {
int c, h;
Node() {}
Node(int _c, int _h) : c(_c), h(_h) {}
}; int main()
{
//freopen("input.txt", "r", stdin);
int iCase;
scanf("%d", &iCase);
while (iCase--) {
scanf("%d%d", &n, &m);
for (int i = ; i < n; i++) {
scanf("%s", gra[i]);
}
memset(height, , sizeof(height));
memset(ans, , sizeof(ans)); for (int i = ; i < n; i++) {
stack<Node> sta;
while (!sta.empty()) sta.pop();
for (int j = ; j < m; j++) {
if (gra[i][j] == '#') {
while (!sta.empty()) sta.pop();
height[j] = ;
}
else {
height[j]++;
Node tmp(j, height[j]);
while (!sta.empty() && sta.top().h >= tmp.h) {
tmp.c = sta.top().c;
sta.pop();
} if (sta.empty()) {
sta.push(tmp);
}
else {
Node top = sta.top();
if (top.h - top.c < tmp.h - tmp.c) sta.push(tmp);
}
Node top = sta.top();
ans[j - top.c + top.h + ]++;
}
}
} for (int i = ; i <= n + m; i++) {
if (ans[i]) printf("%d x %d\n", ans[i], i * );
}
}
return ;
}