前缀和
为什么要学前缀和?
例题:一维前缀和
暴力解法
#include <bits/stdc++.h>
using namespace std;
const int N = 100010;
int n, m;
int a[N];
int main()
{
cin >> n >> m;
for (int i = 1; i <= n; i++) cin >> a[i];
while (m--)
{
int l, r;
cin >> l >> r;
int res = 0;
for (int i = l; i <= r; i++)
{
res += a[i];
}
cout << res << endl;
}
return 0;
}
一维前缀和推导:
\(S_i=a_1+a_2+...+a_i\)
\(S_r-S_{l-1}=a_l+a_{l+1}+...+a_r\)
标准前缀和解法
#include <bits/stdc++.h>
using namespace std;
const int N = 100010;
int n, m;
int a[N], s[N];
int main()
{
cin >> n >> m;
for (int i = 1; i <= n; i++)
{
cin >> a[i];
s[i] = s[i - 1] + a[i];// 初始化了前缀和数组
}
while (m--)
{
int l, r;
cin >> l >> r;
cout << s[r] - s[l - 1] << endl;
}
return 0;
}
例题:二维前缀和
暴力解法
#include <bits/stdc++.h>
using namespace std;
const int N = 1010;
int n, m, q;
int a[N][N];
int main()
{
cin >> n >> m >> q;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++)
cin >> a[i][j];
while (q--)
{
int x1, y1, x2, y2;
cin >> x1 >> y1 >> x2 >> y2;
int res = 0;
for (int i = x1; i <= x2; i++)
for (int j = y1; j <= y2; j++)
res += a[i][j];
cout << res << endl;
}
return 0;
}
二维前缀和推导:
\(S_{i,j}=S_{i-1,j}+S_{i,j-1}-S_{i-1,j-1}+a_{i,j}\)
\(res=S_{x_2,y_2}-S_{x_1-1,y_2}-S_{x_2,y_1-1}+S_{x_1-1,y_1-1}\)
标准二维前缀和解法
#include <bits/stdc++.h>
using namespace std;
const int N = 1010;
int n, m, q;
int a[N][N], s[N][N];
int main()
{
cin >> n >> m >> q;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++)
{
cin >> a[i][j];
s[i][j] = s[i - 1][j] + s[i][j - 1] - s[i - 1][j - 1] + a[i][j]; // 二维前缀和的初始化
}
while (q--)
{
int x1, y1, x2, y2;
cin >> x1 >> y1 >> x2 >> y2;
cout << s[x2][y2] - s[x1 - 1][y2] - s[x2][y1 - 1] + s[x1 - 1][y1 - 1] << endl;
}
return 0;
}
标签:y2,前缀,int,基础,cin,算法,y1,x1
From: https://www.cnblogs.com/yhgm/p/18050605