N - Maximum Subrectangle (前缀和)

You are given two arrays a and b of positive integers, with length n and m respectively.

Let c be an n×m matrix, where ci,j=ai⋅bj.

You need to find a subrectangle of the matrix c such that the sum of its elements is at most x, and its area (the total number of elements) is the largest possible.

Formally, you need to find the largest number s such that it is possible to choose integers x1,x2,y1,y2 subject to 1≤x1≤x2≤n, 1≤y1≤y2≤m, (x2−x1+1)×(y2−y1+1)=s, and ∑ i = x 1 x 2 ∑ i = y 1 y 2 c i , j < = x \sum_{i=x1}^{x2}\sum_{i=y1}^{y2}c_i,_j<=x i=x1x2i=y1y2ci,j<=x
Input
The first line contains two integers n and m (1≤n,m≤2000).

The second line contains n integers a1,a2,…,an (1≤ai≤2000).

The third line contains m integers b1,b2,…,bm (1≤bi≤2000).

The fourth line contains a single integer x (1≤x≤2⋅109).

Output
If it is possible to choose four integers x1,x2,y1,y2 such that 1≤x1≤x2≤n, 1≤y1≤y2≤m, and ∑ i = x 1 x 2 ∑ i = y 1 y 2 c i , j < = x \sum_{i=x1}^{x2}\sum_{i=y1}^{y2}c_i,_j<=x i=x1x2i=y1y2ci,j<=x, output the largest value of (x2−x1+1)×(y2−y1+1) among all such quadruplets, otherwise output 0.

Examples

Input
3 3
1 2 3
1 2 3
9

Output
4

Input
5 1
5 4 2 4 5
2
5

Output
1

Note
Matrix from the first sample and the chosen subrectangle (of blue color):
在这里插入图片描述

Matrix from the second sample and the chosen subrectangle (of blue color):
在这里插入图片描述

题目大意:
给出两个数两组数构成一个矩阵,求该矩阵满足元素和<=x的子矩阵的最大面积为多少

如样例1
3 3
1 2 3
1 2 3
9

构成矩阵
1 2 3
2 4 6
3 6 9

满足元素和<=9的最大子矩阵是
1 2
3 4

面积为2*2=4
所以答案为4

解题思路:
先看3*3矩阵的构成

x0*y0x0*y1x0*y2
x1*y0x1*y1x1*y2
x2*y0x2*y1x2*y2

大矩阵和
sum=x0*y0 + x0*y1 + x0*y2 + x1*y0 + x1*y1 + x1*y2 + x2*y0 + x2*y1 + x2*y2=(x0+x1+x2)*(y0+y1+y2)

容易发现任一一个子矩阵都可以转化成(xn+xn+1+xn+2+…+xn+k1)*(ym+ym+1+ym+2+…+yn+k2)

由此题目可以向前缀和方向思考,求出每个长度前缀的最小值,遍历一边所有结果便可得到答案

完整代码:

#include<iostream>
using namespace std;
int main()
{
	long long n,m;
	long long a[2010],b[2010],a2[2010],b2[2010];
	long long x;
	cin>>n>>m;
	for(int i=1;i<=n;i++){
		cin>>a[i];
		a[i]+=a[i-1];
		a2[i]=(1<<31)-1;  	//初始化 
	}
	for(int i=1;i<=m;i++){
		cin>>b[i];
		b[i]+=b[i-1];
		b2[i]=(1<<31)-1;	//初始化 
	}
	cin>>x;
	for(int i=1;i<=n;i++){		//求每个长度的前缀和最小值 
		for(int j=0;j<=n-i;j++){
			a2[i]=min(a2[i],a[j+i]-a[j]);
		}
	}
	for(int i=1;i<=m;i++){		//求每个长度的前缀和最小值 
		for(int j=0;j<=m-i;j++){
			b2[i]=min(b2[i],b[j+i]-b[j]);
		}
	}
	int ret=0;
	for(int i=1;i<=n;i++){		//遍历数组 
		for(int j=1;j<=m;j++){
			if(a2[i]*b2[j]<=x){
				ret=max(ret,i*j);
			}
		}
	}
	cout<<ret<<endl;
	
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

旧林墨烟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值