Acwing_795前缀和 【一维前缀和】
题目:
代码:
#include <bits/stdc++.h>
#define int long long
#define INF 0X3f3f3f3f
#define endl '\n'
using namespace std;
const int N = 100010;
int arr[N];
int n,m;
int l,r;
signed main(){
std::ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin>>n>>m;
int sum[N];
for(int i = 1; i <= n; i++){
cin>>arr[i];
sum[i]= sum[i-1] + arr[i];
}
while(m--){
cin>>l>>r;
cout<<sum[r]- sum[l-1]<<endl;
}
return 0;
}
【模板】二维前缀和
#include <bits/stdc++.h>
#define int long long
#define endl '\n'
#define INF 0x3f3f3f3f3f
using namespace std;
const int N = 10010;
int arr[N][N],pre[N][N];
int n,c;
signed main(){
std::ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int n,m;
long long k;
cin>>n>>m>>k;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
{
cin>>arr[i][j];
pre[i][j]=pre[i-1][j]+pre[i][j-1]-pre[i-1][j-1]+arr[i][j];
}
}
while(k--){
int x1,y1,x2,y2;
cin>>x1>>y1>>x2>>y2;
cout<<pre[x2][y2]-pre[x1-1][y2]-pre[x2][y1-1]+pre[x1-1][y1-1]<<endl;
}
return 0;
}