前缀和

1
2
3
4
5
//构建前缀和数组
for (int i = 1; i <= n; i ++ )
	s[i] = x + s[i - 1];
//计算某n个连续的数的和
sum = s[i] - s[i - n];

前缀和矩阵

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
//构建前缀和矩阵
for (int i = 1; i <= n; i ++ )
	for (int j = 1; j <= n; j ++ )
	{
		int x;
		scanf("%d", &x);
		s[i][j] = x + s[i - 1][j] + s[i][j - 1] - s[i - 1][j - 1];
	}
//计算矩阵块的和
int get_sum(int x1, int y1, int x2, int y2)
{
    return s[x2][y2] - s[x1 - 1][y2] - s[x2][y1 - 1] + s[x1 - 1][y1 - 1];
}
//计算矩阵块的大小
int get_cnt(int x1, int y1, int x2, int y2)
{
    return (x2 - x1 + 1) * (y2 - y1 + 1);
}