当前位置:网站首页>Acwing4405. 统计子矩阵
Acwing4405. 统计子矩阵
2022-07-17 16:28:00 【理工大猪猪】
给定一个 N×M 的矩阵 A,请你统计有多少个子矩阵 (最小 1×1,最大 N×M) 满足子矩阵中所有数的和不超过给定的整数 K?
输入格式
第一行包含三个整数 N,M 和 K。
之后 N 行每行包含 M 个整数,代表矩阵 A。
输出格式
一个整数代表答案。
数据范围
对于 30% 的数据,N,M≤20,
对于 70% 的数据,N,M≤100,
对于 100% 的数据,1≤N,M≤500;0≤Aij≤1000;1≤K≤250000000。
输入样例:
3 4 10
1 2 3 4
5 6 7 8
9 10 11 12
输出样例:
19
样例解释
满足条件的子矩阵一共有 19,包含:
- 大小为 1×1 的有 10 个。
- 大小为 1×2 的有 3 个。
- 大小为 1×3 的有 2 个。
- 大小为 1×4 的有 1 个。
- 大小为 2×1 的有 3 个。
如果直接用 前缀和 + 暴力,复杂度将是O(N^4),必须优化
优化的方法是:
1)枚举子矩阵的 左边界i 和 右边界j,
2)用 快指针t 枚举 子矩阵的下边界,慢指针s 维护 子矩阵的上边界 (s ≤ t)
3)如果得到的子矩阵的权值和 大于 k,则慢指针s 前进,而子矩阵和必将单调不增
4)慢指针s 继续前进(如图),直到 子矩阵的和 不大于k,慢指针没必要前进了,因为该子矩阵的所有宽度为 j - i + 1 的子矩阵(总共 t - s + 1 种)一定满足要求,更新该情况对答案的贡献 t - s + 1;反之,如果慢指针s越界(s > t),则不操作,直接进入下层循环

#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 1010;
int a[N][N] , qz[N][N] , n , m;
long long int k , sum = 0;
int main()
{
cin >> n >> m >> k;
//前缀和表示
for (int i = 1; i <= n; i ++ )
for (int j = 1; j <= m; j ++ ){
cin >> a[i][j];
//a[i][j] += a[i - 1][j] + a[i][j - 1] - a[i - 1][j - 1];
qz[i][j] = a[i][j] + qz[i - 1][j] + qz[i][j - 1] - qz[i - 1][j - 1];
}
//双指针算法
for(int i = 1; i <= m; i ++){
for(int j = i; j <= m; j ++){
for(int s = 1, t = 1; t <= n; t ++ ){
while(s <= t && qz[t][j] - qz[s - 1][j] - qz[t][i - 1] + qz[s - 1][i - 1] > k) s ++;
if(s <= t) sum += t - s + 1;
}
}
}
cout << sum << endl;
return 0;
}
边栏推荐
猜你喜欢

Opencv based on DLCO descriptor matching

Genesis and bluerun ventures have in-depth exchanges

Simple implementation of scrapy keyword crawler (take Xinhuanet and people's network as examples)

第二天实验

Mysql-1366 - Incorrect string value: ‘\xE5\xBC\xA0\xE4\xB8\x89‘ for column ‘userName‘ at row 1

新一代云数据库的引领者---AWS

NPC, Microsoft, etc. proposed inclusivefl: inclusive federal learning on heterogeneous devices

Nature | the carbon sequestration rate of groundwater is similar to that of oligotrophic marine system

Gradient button function button drawing C language example

Application of semi supervised learning in malware traffic detection
随机推荐
How to apply applet container technology to develop hybrid app
2022年了,跨端技术方案应该怎么选?
HCIP (7)
人大、微软等提出InclusiveFL:异构设备上的包容性联邦学习
Opencv based on DLCO descriptor matching
Relationship and difference between wav and PCM
渐变色按钮功能按钮绘制C语言示例
Energy saving resource allocation strategy based on time-varying graph in satellite networks
一个技巧;教你轻松下载抖音直播视频,抖音直播视频下载新方案!
Hcip second day notes
Solution: function RGB is missing argument $green Problems of
Hcip fourth day notes
How to delay loading JS
C#从入门到精通之第一篇: C#概述与入门
HarmonyoS快速入门:Hello world
Analyze a ros2 cmakelists in detail Txt file
C # from introduction to mastery Part 1: C # overview and introduction
Overview of the application of air, space and sea Association
2022 low voltage electrician examination questions and online simulation examination
[shutter] dart: some features that cannot be ignored