一、思想:有一数组a1,a2……an
其前缀和为si = a1+a2+……+ai
类似于高中的数列sn为a的前n项和
二、前缀和应用
- 求si(预处理)
for(r=1;r<n;r++) s[i]=s[i-1]+a[i];
2.求区间和:【l,r】Sr-Sl-1=al+……ar 算法复杂度为o(1),需先预处理
三、一维前缀和
int n, m;
int a[N], s[N];
int main()
{
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; i ++ ) scanf("%d", &a[i]);
for (int i = 1; i <= n; i ++ ) s[i] = s[i - 1] + a[i]; // 预处理
while (m -- )
{
int l, r;
scanf("%d%d", &l, &r);
printf("%d\n", s[r] - s[l - 1]); // 求区间和
}
return 0;
}
四、二维前缀和
因为x1,x2,y1等均为整数所以应以虚线位置计算面积
∴求和:Sx2y2-Sx2,y1-1-Sx1-1,y2+Sx1-1,y1-1
int n, m, q;
int s[N][N];
int main()
{
scanf("%d%d%d", &n, &m, &q);
for (int i = 1; i <= n; i ++ )
for (int j = 1; j <= m; j ++ )
scanf("%d", &s[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];//预处理
while (q -- )
{
int x1, y1, x2, y2;
scanf("%d%d%d%d", &x1, &y1, &x2, &y2);
printf("%d\n", s[x2][y2] - s[x1 - 1][y2] - s[x2][y1 - 1] + s[x1 - 1][y1 - 1]);//求区间和
}
return 0;
}