标签:names int 模板题 ons stream 直接 ble 理解 code
先上前缀和模板
公式如下
S[i] = a[1] + a[2] + ... a[i]
a[l] + ... + a[r] = S[r] - S[l - 1]
S[i, j] = 第i行j列格子左上部分所有元素的和
以(x1, y1)为左上角,(x2, y2)为右下角的子矩阵的和为:
S[x2, y2] - S[x1 - 1, y2] - S[x2, y1 - 1] + S[x1 - 1, y1 - 1]
Acwing 795.前缀和
来源 : https://www.acwing.com/problem/content/797/
直接套模板,没有什么难点
#include <iostream>
using namespace std;
const int N = 100001 + 10;
int q[N], s[N], n, m;
int main()
{
cin >> n >> m;
for (int i = 1; i <= n; i ++ ) cin >> q[i], s[i] = s[i - 1] + q[i];
while (m -- )
{
int l, r;
cin >> l >> r;
cout << s[r] - s[l - 1] << endl;
}
return 0;
}
Acwing 796.子矩阵的和
来源 : https://www.acwing.com/problem/content/798/
#include <iostream>
using namespace std;
const int N = 1000 + 10;
int a[N][N], s[N][N], n, m, k;
int main()
{
cin >> n >> m >> k;
for (int i = 1; i <= n; i ++ )
for (int j = 1; j <= m; j ++ )
cin >> a[i][j];
for (int i = 1; i <= n; i ++ )
for (int j = 1; j <= m; j ++ )
s[i][j] = s[i - 1][j] + s[i][j - 1] - s[i - 1][j - 1] + a[i][j]; // 通过图像来记忆
while (k -- )
{
int x1, y1, x2, y2;
cin >> x1 >> y1 >> x2 >> y2;
cout << s[x2][y2] - s[x2][y1 - 1] - s[x1 - 1][y2] + s[x1 - 1][y1 - 1] << endl;
}
return 0;
}
标签:names int 模板题 ons stream 直接 ble 理解 code
原文地址:https://www.cnblogs.com/qwer0553/p/13231351.html