一维前缀和
例题
#include <iostream>
using namespace std;
const int N = 1e5 +10 ;
int n,m;
int s[N],num[N];
int main ()
{
cin >> n >> m;
for (int i = 1 ; i <= n; i ++ )
{
cin >> num[i];
s[i] = s[i - 1 ] + num[i];
}
while (m -- )
{
int l,r;
cin >> l >> r;
cout << s[r] - s[l - 1 ] << endl;
}
return 0 ;
}
二维前缀和
例题
using namespace std;
const int N = 1 e3+10 ;
int mat[N][N],s[N][N] ;
int n,m,q ;
int main()
{
cin >> n >> m >> q ;
for (int i = 1 ; i <= n; i ++ )
for (int j = 1 ; j <= m; j ++ )
cin >> mat[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] + mat[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 ;
}
一维差分
例题
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 1e5 +10 ;
int a[N],b[N];
void insert (int l,int r,int c)
{
b[l]+=c;
b[r+1 ]-=c;
}
int main ()
{
int n,m;
cin >> n >> m;
for (int i = 1 ; i <=n; i ++ ) cin >> a[i];
for (int i = 1 ; i <=n; i ++ ) insert (i,i,a[i]);
while (m -- )
{
int l,r,c;
cin >> l >> r >> c;
insert (l,r,c);
}
for (int i = 1 ; i <=n; i ++ )
{
b[i]+=b[i-1 ];
cout << b[i] << " " ;
}
}
二维差分
例题
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 1e3 +10 ;
int a[N][N],b[N][N];
void insert (int x1,int y1,int x2,int y2,int c)
{
b[x1][y1]+=c;
b[x1][y2+1 ]-=c;
b[x2+1 ][y1]-=c;
b[x2+1 ][y2+1 ]+=c;
}
int main ()
{
int n,m,q;
cin >> n >> m >> q;
for (int i = 1 ; i <= n; i ++ )
for (int j = 1 ; j <= m; j ++ )
{
cin >> a[i][j];
insert (i,j,i,j,a[i][j]);
}
while (q -- )
{
int x1,y1,x2,y2,c;
cin >> x1 >> y1 >> x2 >> y2 >> c;
insert (x1,y1,x2,y2,c);
}
for (int i = 1 ; i <= n; i ++ )
for (int j = 1 ; j <= m; j ++)
b[i][j]+=b[i-1 ][j]+b[i][j-1 ]-b[i-1 ][j-1 ];
for (int i = 1 ; i <= n; i ++ )
{
for (int j = 1 ; j <= m; j ++)
cout << b[i][j] << ' ' ;
cout << endl;
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】