一维前缀和
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5+10;
int n , m ;
int a[N] , s[N];
int main()
{
cin >> n >> m ;
for (int i = 1 ; i <= n ; i ++) cin >> a[i];
for (int i = 1 ; i <= n ; i ++) s[i] = s[i - 1] + a[i];
while (m --)
{
int l , r ;
cin >> l >> r ;
int x = s[r] - s[l - 1];
cout << x << endl ;
}
return 0;
}
二维前缀和
#include <bits/stdc++.h>
using namespace std;
const int N = 1010;
int n , m , q ;
int a[N][N] , s[N][N];
int main()
{
cin >> n >> m >> q ;
for (int i = 1 ; i <= n ; i ++)
for (int j = 1 ; j <= m ; j ++)
cin >> a[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] + a[i][j];
while (q --)
{
int x1 , y1 , x2 , y2 ;
cin >> x1 >> y1 >> x2 >> y2;
int x = s[x2][y2] - s[x1 - 1][y2] - s[x2][y1 - 1] + s[x1 -1][y1 - 1];
cout << x << endl ;
}
return 0;
}
一维差分
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5+10;
int n , m ;
int a[N] , s[N] , b[N];//
void fix(int l , int r , int c)//
{
b[l] += c ;
b[r + 1] -= c ;
return ;
}
int main()
{
cin >> n >> m ;
for (int i = 1 ; i <= n ; i ++)
{
cin >> a[i];
fix(i , i , a[i]);
}
while (m --)
{
int l , r , c ;
cin >> l >> r >> c ;
fix(l , r , c) ;
}
for (int i = 1 ; i <= n ; i ++)
{
s[i] = s[i - 1] + b[i];
cout << s[i] << ' ';
}
return 0;
}
二维差分
# include <bits/stdc++.h>
using namespace std;
const int N = 1010 ;
int n , m , q ;
int a[N][N] , s[N][N] , b[N][N];
void fix(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 ;
return ;
}
int main()
{
cin >> n >> m >> q ;
for (int i = 1 ; i <= n ; i ++)
for (int j = 1 ; j <= m ; j ++)
{
cin >> a[i][j];
fix(i , j , i , j , a[i][j]);
}
while (q --)
{
int x1 , y1 , x2 , y2 , c ;
cin >> x1 >> y1 >> x2 >> y2 >> c ;
fix(x1 , y1 , x2 , y2 , c);
}
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] + b[i][j];//
cout << s[i][j] << ' ' ;
}
cout << endl ;
}
return 0;
}