完全版
1 #include <cstdio> 2 #include <cstdio> 3 #include <cstring> 4 #include <algorithm> 5 using namespace std; 6 int lowbit(int x) 7 { 8 return x&(-x); 9 } 10 struct tree_arr 11 { 12 int c[1005]; 13 tree_arr() 14 { 15 clear(); 16 } 17 void clear() 18 { 19 memset(c,0,sizeof(c)); 20 } 21 int get_sum(int x) 22 { 23 int sum=0; 24 while(x) 25 { 26 sum+=c[x]; 27 x-=lowbit(x); 28 } 29 return sum; 30 } 31 void update(int x,int d,int n) 32 { 33 while(x<=n) 34 { 35 c[x]+=d; 36 x+=lowbit(x); 37 } 38 } 39 } r[1005]; 40 int get_sum(int x,int y)///(x,y) 41 { 42 int sum=0; 43 while(x) 44 { 45 sum+=r[x].get_sum(y); 46 x-=lowbit(x); 47 } 48 return sum; 49 } 50 void update(int x,int y,int d,int n,int m)///n行,m列 51 { 52 while(x<=n) 53 { 54 r[x].update(y,d,m); 55 x+=lowbit(x); 56 } 57 58 } 59 int main() 60 { 61 int i,j,n=10,m=10; 62 memset(r,0,sizeof(r)); 63 for(i=1; i<=n; i++) 64 { 65 for(j=1; j<=m; j++) 66 { 67 update(i,j,1,n,m); 68 } 69 } 70 for(i=1; i<=n; i++) 71 { 72 for(j=1; j<=m; j++) 73 { 74 printf("%3d ",get_sum(i,j)); 75 } 76 puts(""); 77 } 78 return 0; 79 }
简化版
1 int c[MAX][MAX]; 2 int n,m; 3 int Lowbit(int x) 4 { 5 return x & (-x); 6 } 7 void Updata(int x,int y,int d) 8 { 9 int i,k; 10 for(i=x; i<=n; i+=Lowbit(i)) 11 for(k=y; k<=m; k+=Lowbit(k)) 12 c[i][k]+=d; 13 } 14 int Get(int x,int y) 15 { 16 int i,k,sum = 0; 17 for(i=x; i>0; i-=Lowbit(i)) 18 for(k=y; k>0; k-=Lowbit(k)) 19 sum += c[i][k]; 20 return sum; 21 }
时间: 2024-10-25 06:02:31