目录
一、一维前缀和
1.前缀和(模板)

答案如下:
cpp
#include<iostream>
#include<vector>
using namespace std;
const int N = 1e5 + 10;
long long a[N];
int main()
{
int n,m;
a[0] = 0;
cin >> n >>m;
for(int i = 1; i <= n; i++)
{
int e; cin >> e;
a[i] = e + a[i-1];
}
while(m--)
{
int l,r;
cin >> l >> r;
long long sum = a[r] - a[l-1];
cout << sum << endl;
}
return 0;
}
2.最大子段和

答案如下:
cpp
#include<iostream>
using namespace std;
const int N = 2e5 + 10;
int a[N];
int main()
{
int n; cin >> n;
for(int i = 1; i <= n; i++)
{
cin >> a[i];
}
int cnt = 0;
int max = -1e5;
for(int i = 1; i <= n; i++)
{
cnt += a[i];
max = max < cnt ? cnt : max;
if(cnt < 0) cnt = 0;
}
cout << max;
return 0;
}
二、二维前缀和
1.二维前缀和(模板)

答案如下:
cpp
#include<iostream>
using namespace std;
const int N = 1e3 + 10;
long long arr[N][N];
int main()
{
int n,m,q;
cin >> n >> m >> q;
for(int i = 1; i <= n; ++i)
{
for(int j = 1; j <= m; ++j)
{
int e; cin >> e;
arr[i][j] = arr[i][j-1] + arr[i-1][j] - arr[i-1][j-1] + e;
}
}
while(q--)
{
int x1,y1,x2,y2;
cin >> x1 >> y1 >> x2 >> y2;
long long sum = arr[x2][y2] - arr[x2][y1-1] - arr[x1-1][y2] + arr[x1-1][y1-1];
cout << sum << endl;
}
return 0;
}
2.激光炸弹

答案如下:
cpp
#include<iostream>
using namespace std;
const int N = 5010;
int a[N][N];
int f[N][N];
int main()
{
int n,m;
cin >> n >> m;
while(n--)
{
int x,y,v;
cin >> x >> y >> v;
x++; y++;
a[x][y] += v;
}
n = 5001;
for(int i = 1; i <= n; i++)
{
for(int j = 1; j <= n; j++)
{
f[i][j] = f[i][j-1] + f[i-1][j] - f[i-1][j-1] + a[i][j];
}
}
int ret = 0;
m = min(m,n);
for(int i = m; i <= n; i++)
{
int x1 = i - m + 1;
for(int j = m; j <= n; j++)
{
int y1 = j - m + 1;
ret = max(ret,f[i][j] - f[i][y1-1] - f[x1-1][j] + f[x1-1][y1-1]);
}
}
cout << ret << endl;
return 0;
}