Introduction to the Tree-like array "algorithmic Competition introductory Classic training guide"
One-dimensional version:
Los Valleys 3374
Links: https://www.luogu.org/problem/show?pid=3374
Analysis: tree-like Arrays Bare Template questions
1#include <iostream>2#include <cstdio>3#include <cstring>4 using namespacestd;5 Const intmaxn=500000+Ten;6 intc[maxn];7 intn,m;8 intLowbit (intx) {9 returnx& (-x);Ten } one voidAddintXintD) { a while(x<=N) { -c[x]+=d; x+=lowbit (x); - } the } - intSumintx) { - intret=0; - while(x>0){ +ret+=c[x]; x-=lowbit (x); - } + returnret; a } at intMain () - { -Cin>>n>>m; -Memset (c,0,sizeof(c)); - for(intI=1; i<=n;i++){ - intx; inscanf"%d",&x); - Add (i,x); to } + while(m--){ - intnum,a,b; thescanf"%d%d%d",&num,&a,&b); * if(num==1){ $ Add (a, b);Panax Notoginseng}Else{ -printf"%d\n", Sum (b)-sum (a-1)); the } + } a return 0; the}
View Code
Two-dimensional version:
vijos1512
Links: https://vijos.org/p/1512
Analysis: a two-dimensional tree-shaped array of bare topics, the calculation of the area of attention
1#include <iostream>2#include <cstdio>3#include <cstring>4#include <string>5#include <cmath>6 using namespacestd;7 Const intmaxn= -;8 intc[maxn][maxn];9 intn,m;Ten intLowbit (intx) { one returnx& (-x); a } - voidAddintXintYintD) { - for(inti=x;i<=n;i+=lowbit (I)) the for(intj=y;j<=n;j+=lowbit (j)) -c[i][j]+=d; - } - intSumintXintY) { + intret=0; - for(intI=x;i>0; i-=lowbit (I)) + for(intJ=y;j>0; j-=lowbit (j)) aret+=c[i][j]; at returnret; - } - intMain () - { -scanf"%d",&n); -Memset (c,0,sizeof(c)); in while(SCANF ("%d", &m)! =EOF) { - if(m==3) break; to if(m==1){ + intx,y,k; -scanf"%d%d%d",&x,&y,&k); theAdd (x+1, y+1, k); *}Else{ $ intx1,y1,x2,y2;Panax Notoginsengscanf"%d%d%d%d",&x1,&y1,&x2,&y2); - intCnt=sum (x2+1, y2+1)-sum (x1,y2+1)-sum (x2+1, Y1) +sum (x1,y1); theprintf"%d\n", cnt); + } a } the return 0; +}
View Code
Tree-like Array Basics