BUG写手


私信TA

用户名:uq_19400307891

访问量:3027

签 名:

等  级
排  名 2377
经  验 2241
参赛次数 0
文章发表 9
年  龄 18
在职情况 学生
学  校 武汉商学院
专  业 物联网工程

  自我简介:

正在努力变强的大一萌新ACMer

解题思路:

先进行预处理,把每一列矩阵进行压缩,即a[i][j]等于原矩阵第j列第1行到第i行的和。

三层for循环,第一层枚举子矩阵的起始行b,第二层枚举子矩阵的终点行i,第三层枚举子矩阵的终点列r。

起始列l初始为1,如果当前和超过了k,则使起始列l自增1,直到当前和不大于k。

答案数量每次加循环r-l+1。即当前起始行b、结束行i的情况下,以r为结束列的,和不大于k的子矩阵数量。


参考代码(C++):

#include <bits/stdc++.h>
using namespace std;
#define endl '\n'
#define int long long
typedef unsigned long long ull;
const int maxn = 510;
const int INF = 0x3fffffff;
int n, m, k, a[maxn][maxn]; // a维护每列的前缀和

signed main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    cout << fixed;
    cout.precision(18);

    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];  // 将每一列的和压缩
        }
    }
    int ans = 0;
    for (int b = 1; b <= n; b++)  // 枚举子矩阵起始行
    {  
        for (int i = b; i <= n; i++)  // 枚举子矩阵终点行
        {
            int s = 0;
            for (int r = 1, l = 1; r <= m; r++)  // 枚举子矩阵结束列
            {
                s += a[i][r] - a[b - 1][r];
                while(s > k)
                {
                    s -= a[i][l] - a[b - 1][l];
                    l++;
                }
                ans += r - l + 1;
            }
        }
    }
    cout << ans << endl;
    return 0;
}


 

0.0分

2 人评分

看不懂代码?想转换其他语言的代码? 或者想问其他问题? 试试问问AI编程助手,随时响应你的问题:

编程语言转换万能编程问答  

代码解释器

代码纠错

SQL生成与解释

  评论区