zoukankan      html  css  js  c++  java
  • 二维树状数组模板(区间修改+区间查询)

    二维树状数组模板(区间修改+区间查询)

    例题: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){
    	return
    		calc(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
    ",query(X1 , Y1 , X2 , Y2 ));
    	}return 0;return 0;
    	
    }
    

  • 相关阅读:
    android自定义控件onLayout方法
    android自定义控件onMeasure方法
    activity的四种启动模式详细分析
    android屏幕适配的全攻略2--支持手机各种屏幕密度dpi
    android屏幕适配的全攻略3-动态获取手机屏幕宽高及动态设置控件宽高
    DIV滚动条
    .NET面试题6
    .NET面试题5
    .NET面试题4
    .NET面试题2
  • 原文地址:https://www.cnblogs.com/Guess2/p/8459568.html
Copyright © 2011-2022 走看看