[关闭]
@zhangche0526 2017-02-25T06:36:25.000000Z 字数 1764 阅读 826

线段树

  1. #include<iostream>
  2. #include<cstdio>
  3. using namespace std;
  4. const int INF=1e9,MAXN=1000;
  5. struct node{int a,b,lc,rc;} tree[MAXN+1];
  6. struct lazy{int ch,det} tag[MAXN+1];
  7. int na[MAXN+1],sum[MAXN+1],mx[MAXN+1];
  8. int n,cnt,root;
  9. void update(now)
  10. {
  11. int lc=tree[now].lc,rc=tree[now].rc;
  12. mx=max(mx[lc],mx[rc]);
  13. sum=su[lc]+su[rc];
  14. }
  15. void buildTree(int l,int r)//递归建树
  16. {
  17. cnt++;
  18. int now=cnt;//由于cnt在递归过程中会发生改变,所以需要now记录当前的cnt
  19. tree[now].a=l,tree[now].b=r;
  20. if(l==r)
  21. {
  22. mx[now]=na[l],sum[now]=na[l];
  23. return now;
  24. }
  25. int mid=(l+r)>>1;
  26. tree[now].lc=build(l,mid);
  27. tree[now].rc=build(mid+1,r);
  28. update(now);
  29. return now;
  30. }
  31. void pushDown(int o)
  32. {
  33. int lc=tree[o].lc,rc=tree[o].rc;
  34. if(tag[o].ch)
  35. {
  36. mx[o]=tag[o].ch;
  37. sum[o]=(tree[o].b-tree[o].a+1)*tag[o].ch;
  38. if(lc) tag[lc].ch=tag[o].ch;
  39. if(rc) tag[rc].ch=tag[o].ch;
  40. tag[o].ch=0;
  41. }
  42. if(tag[o].det)
  43. {
  44. mx[o]+=tag[o].det;
  45. su[o]+=(tree[o].b-tree[o].a+1]*tag[o].det;
  46. if(lc) tag[lc].det+=tag[o].det;
  47. if(rc) tag[rc].det+=tag[o].det;
  48. tag[o].det=0;
  49. }
  50. }
  51. int ql,qr;//询问的范围
  52. int calMax(int o,int l,int r)
  53. {
  54. pushDown(o);
  55. if(ql<=l&&r<=qr) return mx[o];
  56. int mid=(l+r)>>1,lmx=-INF,rmx=-INF;
  57. if(ql<=mid) lmx=calMax(tree[o].lc,l,mid);
  58. if(qr>mid) rmx=calMax(tree[o].rc,mid+1,r);
  59. return max(lmx,rmx);
  60. }
  61. int calSum(int o,int l,int r)
  62. {
  63. pushDown(o);
  64. if(ql<=l&&r<=qr) return sum[o];
  65. int mid=(l+r)>>1,sum=0;
  66. if(ql<=mid) sum+=calSum(tree[o].lc,l,mid);
  67. if(qr>mid) sum+=calSum(tree[o].rc,mid+1,r);
  68. return sum;
  69. }
  70. int cl,cr;//更改的范围
  71. void chCh(int o,int l,int r,int x)
  72. {
  73. pushDown(o);
  74. if(cl<=l&&r<=cr)
  75. {
  76. mx[o]=x;
  77. sum[o]=(r-l+1)*x;
  78. tag[tree[o].lc].ch=x,tag[tree[o]].ch=x;
  79. return;
  80. }
  81. int mid=(l+r)>>1;
  82. if(cl<=mid) chCh(tree[o].lc,l,mid);
  83. if(cr>mid) chCh(tree[o].rc,mid+1,r);
  84. update(o);
  85. }
  86. void chDet(int o,int l,int r,int x)
  87. {
  88. pushdown(o);
  89. if(cl<=l&&r<=cr)
  90. {
  91. mx[o]+=x;
  92. sum[o]+=(r-l+1)*x;
  93. tag[tree[o].lc].det+=x,tag[tree[o]].det+=x;
  94. return;
  95. }
  96. int mid=(l+r)>>1;
  97. if(cl<=mid) chDet(tree[o].lc,l,mid);
  98. if(cr>mid) chDet(tree[o].rc,mid+1,r);
  99. update(o);
  100. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注