SPOJ MINSUB 二分+单调栈

12 篇文章 0 订阅
3 篇文章 0 订阅

Largest Submatrix

no tags 

You are given an matrix M (consisting of nonnegative integers) and an integer K.  For any submatrix of M' of M define min(M') to be the minimum value of all the entries of M'.  Now your task is simple:  find the maximum value of min(M') where M' is a submatrix of M of area at least K (where the area of a submatrix is equal to the number of rows times the number of columns it has).

Input

The first line contains a single integer T (T ≤ 10) denoting the number of test cases, T test cases follow.  Each test case starts with a line containing three integers, R (R ≤ 1000), C (C ≤ 1000) and K (K ≤ R * C) which represent the number of rows, columns of the matrix and the parameter K.  Then follow R lines each containing C nonnegative integers, representing the elements of the matrix M.  Each element of M is ≤ 10^9

Output

For each test case output two integers:  the maximum value of min(M'), where M' is a submatrix of M of area at least K, and the maximum area of a submatrix which attains the maximum value of min(M').  Output a single space between the two integers.

Example

Input:
2
2 2 2
1 1
1 1
3 3 2
1 2 3
4 5 6
7 8 9

Output:
1 4
8 2
题意:给你一个矩阵  找出一个子矩阵  面积至少为k的情况下里面的最小值最大


题解:二分答案  对于每次二分  创造出一个新的01矩阵  1代表当前为比此答案大  0代表小  问题就转化成了最大01子矩阵

用单调栈求解子矩阵


#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int n,m,k;
int a[1005][1005],b[1005][1005],d[1005],lef[1005][1005],rig[1005][1005];
int solve(int x) {
    int i,j,ans;ans=0;  
    for(j=1;j<=m;j++)b[1][j]=(a[1][j]>=x);  
    for(i=2;i<=n;i++)for(j=1;j<=m;j++)b[i][j]=(a[i][j]>=x)?(1+b[i-1][j]):0;  
    for(i=1;i<=n;i++)  
    {  
    	d[0]=1;
        d[1]=lef[i][1]=1;  
        for(j=2;j<=m;j++)  
        {  
            while(d[0]>0&&b[i][d[d[0]]]>=b[i][j])d[0]--;  
            lef[i][j]=(d[0])?(d[d[0]]+1):1;d[++d[0]]=j;  
        }  
        d[d[0]=1]=rig[i][m]=m;  
        for(j=m-1;j>=1;j--)  
        {  
            while(d[0]>0&&b[i][d[d[0]]]>=b[i][j])d[0]--;  
            rig[i][j]=(d[0])?(d[d[0]]-1):m;d[++d[0]]=j;  
        }  
        for(j=1;j<=m;j++)if(b[i][j])ans=max(ans,b[i][j]*(rig[i][j]-lef[i][j]+1));  
    }  
    return (ans>=k)?ans:0;  
}  
int main(){
	int t,i,j;
	scanf("%d",&t);
	while(t--){
		scanf("%d%d%d",&n,&m,&k);
		for(i=1;i<=n;i++){
			for(j=1;j<=m;j++)scanf("%d",&a[i][j]);
		}
		int l=0,r=1000000000;
		while(l+1<r){
			int mid=(l+r)/2;
			if(solve(mid))l=mid;
			else r=mid;
		}
		if(solve(r))l=r;
		printf("%d %d\n",l,solve(l));
	}
	return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值