NOJ1538——[1538] K-Submartix

此博客讨论如何在给定矩阵中找到一个满足特定条件的最小面积子矩阵。通过前缀和技巧优化搜索过程,实现高效求解。
  • 问题描述
  • You are given a matrix consisting of some integer, its size is n*m.
    You should find a minimum area submatrix that the sum of the submatrix (sum of all elements in the submatrix) is not less k.
  • 输入
  • The input contains multiple test cases. Each test case begins with n, m (1 <= n, m <= 250) and k (-10^9 <= k <= 10^9) on line. Next n lines contain m integer each matrix . The input ends once EOF is met.
  • 输出
  • Print a single integer -- the area of the minimum obtained submatrix. If we cannot obtain a matrix of sum is not less k, print -1.
  • 样例输入
  • 4 4 10
    1 2 3 4
    5 6 7 8
    9 10 11 12
    13 14 15 16
    1 3 15
    10 -5 10
    2 2 10
    1 2
    2 3
  • 样例输出
  • 1
    3
    -1
  • 提示
  • 来源
  • wk@NJUPT

   这题就是让你求一个满足矩阵元素和大于等于k,然后面积最小的矩阵,输出最小面积,如果不存在,就输出-1,

我的思路是,想办法把二维的问题化成一维。所以我需要一个数组sum[i][j],表示第j列从第1行到第i行的元素和。

之后我们枚举矩阵的上下界,利用前缀和的思想,另开一维数组array[],存的就是前i列的和,接下来就是去判断,然后求最小值了。

#include<stdio.h>
#include<string.h>
#include<iostream>
#include<algorithm>

using namespace std;

const int maxn=270;

int sum[maxn][maxn];
int array[maxn];
int mat[maxn][maxn];
int main()
{
int n,m,k;
while(~scanf("%d%d%d",&n,&m,&k))
{
memset(sum,0,sizeof(sum));
array[0]=0;
int area=0x3f3f3f3f;
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++)
{
scanf("%d",&mat[i][j]);
sum[i][j]=sum[i-1][j]+mat[i][j];
}
for(int up=1;up<=n;up++)
for(int down=up;down<=n;down++)
{
for(int i=1;i<=m;i++)
{
array[i]=array[i-1]+sum[down][i]-sum[up-1][i];
if(array[i]<k)//也算是个剪枝了,之前没写直接TLE
continue;
for(int j=i-1;j>=0;j--)
if(array[i]-array[j]>=k)
{
area=min(area,(i-j)*(down-up+1));
break;
}
}
}
if(area==0x3f3f3f3f)
printf("-1\n");
else
printf("%d\n",area );
}
return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值