当前位置:网站首页>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基于DLCO描述子匹配
- C#从入门到精通之第一篇: C#概述与入门
- 深度学习参数初始化(二)Kaiming初始化 含代码
- How to run SH script file
- 如何应用小程序容器技术开发Hybrid App
- Leetcode 20. 有效的括号
- ros(26):ros::Time::now(),ros::Duration,toSec(),toNSec(); Calculate program execution time
- Hcip fourth day notes
- 李宏毅《机器学习》|1. Introduction of this course(机器学习介绍)
- Mysql-1366 - Incorrect string value: ‘\xE5\xBC\xA0\xE4\xB8\x89‘ for column ‘userName‘ at row 1
猜你喜欢

Solution: code error: error reported by error could not resolve

Linux下MySQL的安装与使用

A skill; Teach you to easily download Tiktok live video, Tiktok live video download new scheme!

Experiment the next day

渐变色按钮功能按钮绘制C语言示例

Will webgpu become the killer of webgl?

psd. JS parsing PSD file

Configuring OSPF experiment in mGRE environment

机器学习(上)吴恩达

Mysql-1366 - Incorrect string value: ‘\xE5\xBC\xA0\xE4\xB8\x89‘ for column ‘userName‘ at row 1
随机推荐
HCIP(5)
OpenCV基于DLCO描述子匹配
One click backup of files
PPPoE拨号上网
ros(26):ros::Time::now(),ros::Duration,toSec(),toNSec();计算程序执行时间
Genesis and bluerun ventures have in-depth exchanges
Swiftui data persistence in swift, different methods of saving data
HCIP (7)
Research on downlink spectrum efficiency of 6G space earth integrated network high altitude platform base station
Understanding of rapid exploring random trees (RRT) path planning method
C#从入门到精通之第二篇: C# 基础语法
Leetcode 150. 逆波兰表达式求值
GET 请求和 POST 请求的区别和使用
阿趣的思考
七月集训(第17天) —— 广度优先搜索
【C语言编程7】BTB模型
Softmax和Cross-entropy是什么关系?
Create a custom palette in swiftui color tutorial
Thoughts on ahe investment
hcip第四天笔记