UVA12265-Selling Land(单调栈)

Problem UVA12265-Selling Land

Accept: 137  Submit: 782
Time Limit: 3000 mSec

UVA12265-Selling Land(单调栈) Problem Description

UVA12265-Selling Land(单调栈)

UVA12265-Selling Land(单调栈) 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).

UVA12265-Selling Land(单调栈) Output

Per test case:
• Zero or more lines containing a complete list of how many parcels of each perimeter Per needs to sell in order to maximize his profit. More specifically, if Per should sell pi parcels of perimeter i in the optimal solution, output a single line ‘pixi’. The lines should be sorted in increasing order of i. No two lines should have the same value of i, and you should not output lines with pi = 0.
 

UVA12265-Selling Land(单调栈) Sample Input

1
6 5
..#.#
.#...
#..##
...#.
#....
#..#.
 

UVA12265-Selling Land(单调栈) 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 ;
}
上一篇:pandas 读写 Excel 格式的数据


下一篇:Java中的五种单例模式实现方法