题目:
https://vjudge.net/problem/SPOJ-MINSUB
一开始并不会做,然后看了看下面的题解:
http://blog.youkuaiyun.com/just_sort/article/details/54135267
然后大体思想理解了,之前写单调栈一直都是用stack<node>,node里记录向前延伸向后延伸以及当前的数值和位置,写这个题的时候觉得用这种方法写起来比较麻烦,然后尝试去使用题解中的方法,单调栈可以像这篇题解中使用一个数组来模拟栈,同时分两次遍历数组并统计每个元素的向前延伸和向后延伸,也是一种比较简单的写法。此类题目基本都可以用二分来解决,最后注意二分的取值。
附上代码:
#include <iostream>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <cstring>
#include <vector>
#include <list>
#include <map>
#include <queue>
#include <stack>
#include <bitset>
#include <sstream>
#include <algorithm>
#include <numeric>
#include <functional>
//#include <iomanip.h>
#include <limits.h>
//#include <strstrea.h>
//#include <fstream.h>
#define ll long long
#define ull unsigned long long
//#define int64 long long
#define INF 0x3f3f3f3f
using namespace std;
const int maxn = 1e3 + 5;
int t, n, m, k;
int a[maxn][maxn], b[maxn][maxn], l[maxn][maxn], r[maxn][maxn], st[maxn], top;
int check(int x) {
int ans = 0;
for (int j = 1; j <= m; j++) b[1][j] = (a[1][j] >= x);
for (int i = 2; i <= n; i++) {
for (int j = 1; j <= m; j++) {
b[i][j] = (a[i][j] >= x) ? (b[i - 1][j] + 1) : 0;
}
}
for (int i = 1; i <= n; i++) {
top = st[1] = l[i][1] = 1;
for (int j = 2; j <= m; j++) {
while (top > 0 && b[i][st[top]] >= b[i][j]) top--;
l[i][j] = (top) ? (st[top] + 1) : 1;
st[++top] = j;
}
top = 1;
st[1] = r[i][m] = m;
for (int j = m - 1; j >= 1; j--) {
while (top > 0 && b[i][st[top]] >= b[i][j]) top--;
r[i][j] = (top) ? (st[top] - 1) : m;
st[++top] = j;
}
for (int j = 1; j <= m; j++) {
if (b[i][j]) ans = max(ans, b[i][j] * (r[i][j] - l[i][j] + 1));
}
}
return ans;
}
int main() {
//freopen("in.txt", "r", stdin);
//freopen("data.out", "w", stdout);
cin >> t;
while (t--) {
cin >> n >> m >> k;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++)
cin >> a[i][j];
int l = 0, r = 1e9, mid;
int mmax;
while (l < r) {
mid = (l + r) >> 1;
if (check(mid) >= k) l = mid + 1, mmax = mid;
else r = mid;
}
cout << mmax << " " << check(mmax) << endl;
}
//fclose(stdin);
//fclose(stdout);
return 0;
}