二维树状数组模板(区间修改+区间查询)
例题:JOIOI上帝造题的七分钟
一共两种操作:
\(L\ x_1\ y_1\ x_2\ y_2\ d\):把\((x_1,y_1)\),\((x_2,y_2)\)这个矩形内所有元素加\(d\)。
\(k\ x_1\ y_1\ x_2\ y_2\):查询\((x_1,y_1)\),\((x_2,y_2)\)这个矩形内所有元素的和。
代码如下:
#include<bits/stdc++.h>
#define RG register
#define IL inline
#define _ 2050
#define ll long long
//#define ll int
using namespace std;ll n , m , c1[_][_],c2[_][_],c3[_][_],c4[_][_] ;IL void upt(ll x , ll y , ll dt){for(RG int i = x; i <= n; i += (i & -i) )for(RG ll j = y; j <= m; j += (j & -j)){c1[ i ][ j ] += dt ;c2[ i ][ j ] += dt * y;c3[ i ][ j ] += dt * x;c4[ i ][ j ] += dt * x * y;}
}
IL ll calc(ll x,ll y){RG ll res = 0;for(RG ll i = x; i > 0; i -= (i & -i))for(RG ll j = y; j > 0; j -= (j & -j)){res = res+ (x + 1) * (y + 1) * c1[ i ][ j ]- (x + 1) * c2[ i ][ j ]- (y + 1) * c3[ i ][ j ]+ c4[ i ][ j ] ; }return res;
}IL void add(ll X1,ll Y1,ll X2,ll Y2,ll dt){upt(X1 , Y1 , dt ) ;upt(X2 + 1 , Y1 , -dt ) ;upt(X1 , Y2 + 1, -dt ) ;upt(X2 + 1, Y2 + 1, dt ) ;
}
IL ll query(ll X1,ll Y1,ll X2,ll Y2){returncalc(X2 , Y2) + calc(X1 - 1, Y1 - 1) -calc(X1 - 1 , Y2) - calc(X2 , Y1 - 1) ;
}int main(){ll X1 , X2 , Y1 , Y2 , z; char c[3]; scanf("X %lld %lld",&n,&m);while(scanf("%s",c)!=EOF){scanf("%lld%lld%lld%lld", &X1, &Y1, &X2, &Y2);if(c[0]=='L'){scanf("%lld", &z);add(X1 , Y1 , X2 , Y2 , z);}else printf("%lld\n",query(X1 , Y1 , X2 , Y2 ));}return 0;return 0;}