題目鏈接:
http://www.spoj.com/problems/MINSUB/
題意:
給定一個由非負數組成的矩陣M,和一個整數K,對於矩陣M的子矩陣M’,定義min(M’)爲M’矩陣中元素的最小值。
我們需要找出這樣一個子矩陣,該矩陣的面積至少爲K,且min(M’)最大化。面積的定義爲該矩陣的行數*列數。求出min(M’),並給出使得min(M’)爲該值時面積的最大值。
題解:
這類問題都是可以二分答案的。把小於二分值的位置設爲0,其他設爲1,那麼問題就變成了求全爲1的子矩陣的最大面積,這件事情可以用單調棧搞(方法類似於http://www.cnblogs.com/ziyi–caolu/archive/2013/06/23/3151556.html ,事先統計出每個位置向左有多少個1)。可以預處理出每個點(i,j)的左邊有多少個連續的1(記爲f[i][j]),然後枚舉每一列,那麼這一列就可以類似與單調棧一樣處理算出能上下延伸多少,做法和一 數組的單調棧一樣。
代碼:
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define MS(a) memset(a,0,sizeof(a))
#define MP make_pair
#define PB push_back
const int INF = 0x3f3f3f3f;
const ll INFLL = 0x3f3f3f3f3f3f3f3fLL;
inline ll read(){
ll x=0,f=1;char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
return x*f;
}
//////////////////////////////////////////////////////////////////////////
const int maxn = 1e5+10;
int n,m,k;
int a[1005][1005],f[1005][1005];
struct node{
int v,pre,nxt;
node(int v) : v(v),pre(1),nxt(1) {}
};
ll calc(int x){
MS(f);
for(int i=1; i<=n; i++)
for(int j=1; j<=m; j++)
if(a[i][j]>=x) f[i][j] = f[i][j-1]+1;
ll ans = -1;
for(int j=1; j<=m; j++){
stack<node> s;
s.push(node(f[1][j]));
for(int i=2; i<=n; i++){
node t = node{f[i][j]};
while(!s.empty() && t.v<=s.top().v){
node tt=s.top(); s.pop();
if(!s.empty()) s.top().nxt += tt.nxt;
t.pre += tt.pre;
ll tmp = tt.v * (tt.pre+tt.nxt-1);
if(tmp>ans && tmp>=k)
ans = tmp;
}
s.push(t);
}
while(!s.empty()){
node tt = s.top(); s.pop();
if(!s.empty()) s.top().nxt += tt.nxt;
ll tmp = tt.v * (tt.pre+tt.nxt-1);
if(tmp>ans && tmp>=k)
ans = tmp;
}
}
return ans;
}
int main(){
int T = read();
while(T--){
int mi = INF, mx = -INF;
cin >> n >> m >> k;
for(int i=1; i<=n; i++)
for(int j=1; j<=m; j++){
cin >> a[i][j];
mi = min(mi,a[i][j]);
mx = max(mx,a[i][j]);
}
ll ans1=0,ans2=0;
int L=mi,R=mx;
while(L<=R){
int mid = (L+R)/2;
ll tmp = calc(mid);
if(tmp!=-1) ans1=mid,ans2=tmp,L=mid+1;
else R=mid-1;
}
cout << ans1 << " " << ans2 << endl;
}
return 0;
}