线段树(转)

线段树

 

转载请注明出处,谢谢!http://blog.csdn.net/metalseed/article/details/8039326 

持续更新中···

 

一:线段树基本概念

1:概述

线段树,类似区间树,是一个完全二叉树,它在各个节点保存一条线段(数组中的一段子数组),主要用于高效解决连续区间的动态查询问题,由于二叉结构的特性,它基本能保持每个操作的复杂度为O(lgN)!

性质:父亲的区间是[a,b],(c=(a+b)/2)左儿子的区间是[a,c],右儿子的区间是[c+1,b],线段树需要的空间为数组大小的四倍

2:基本操作(demo用的是查询区间最小值)

线段树的主要操作有:

(1):线段树的构造 void build(int node, int begin, int end);

主要思想是递归构造,如果当前节点记录的区间只有一个值,则直接赋值,否则递归构造左右子树,最后回溯的时候给当前节点赋值

[cpp] view plaincopyprint?

  1. #include <iostream>
  2. using namespace std;
  3. const int maxind = 256;
  4. int segTree[maxind * 4 + 10];
  5. int array[maxind];
  6. /* 构造函数,得到线段树 */
  7. void build(int node, int begin, int end)
  8. {
  9. if (begin == end)
  10. segTree[node] = array[begin]; /* 只有一个元素,节点记录该单元素 */
  11. else
  12. {
  13. /* 递归构造左右子树 */
  14. build(2*node, begin, (begin+end)/2);
  15. build(2*node+1, (begin+end)/2+1, end);
  16. /* 回溯时得到当前node节点的线段信息 */
  17. if (segTree[2 * node] <= segTree[2 * node + 1])
  18. segTree[node] = segTree[2 * node];
  19. else
  20. segTree[node] = segTree[2 * node + 1];
  21. }
  22. }
  23. int main()
  24. {
  25. array[0] = 1, array[1] = 2,array[2] = 2, array[3] = 4, array[4] = 1, array[5] = 3;
  26. build(1, 0, 5);
  27. for(int i = 1; i<=20; ++i)
  28. cout<< "seg"<< i << "=" <<segTree[i] <<endl;
  29. return 0;
  30. }
#include <iostream>
using namespace std;

const int maxind = 256;
int segTree[maxind * 4 + 10];
int array[maxind];
/* 构造函数,得到线段树 */
void build(int node, int begin, int end)
{
    if (begin == end)
        segTree[node] = array[begin]; /* 只有一个元素,节点记录该单元素 */
    else
    {
    	/* 递归构造左右子树 */
        build(2*node, begin, (begin+end)/2);
        build(2*node+1, (begin+end)/2+1, end); 

		/* 回溯时得到当前node节点的线段信息 */
	    if (segTree[2 * node] <= segTree[2 * node + 1])
	        segTree[node] = segTree[2 * node];
	    else
	        segTree[node] = segTree[2 * node + 1];
    }
}

int main()
{
	array[0] = 1, array[1] = 2,array[2] = 2, array[3] = 4, array[4] = 1, array[5] = 3;
	build(1, 0, 5);
	for(int i = 1; i<=20; ++i)
	 cout<< "seg"<< i << "=" <<segTree[i] <<endl;
	return 0;
} 

此build构造成的树如图:

(2):区间查询int query(int node, int begin, int end, int left, int right);

(其中node为当前查询节点,begin,end为当前节点存储的区间,left,right为此次query所要查询的区间)

主要思想是把所要查询的区间[a,b]划分为线段树上的节点,然后将这些节点代表的区间合并起来得到所需信息

比如前面一个图中所示的树,如果询问区间是[0,2],或者询问的区间是[3,3],不难直接找到对应的节点回答这一问题。但并不是所有的提问都这么容易回答,比如[0,3],就没有哪一个节点记录了这个区间的最小值。当然,解决方法也不难找到:把[0,2]和[3,3]两个区间(它们在整数意义上是相连的两个区间)的最小值“合并”起来,也就是求这两个最小值的最小值,就能求出[0,3]范围的最小值。同理,对于其他询问的区间,也都可以找到若干个相连的区间,合并后可以得到询问的区间。

[cpp] view plaincopyprint?

  1. int query(int node, int begin, int end, int left, int right)
  2. {
  3. int p1, p2;
  4. /*  查询区间和要求的区间没有交集  */
  5. if (left > end || right < begin)
  6. return -1;
  7. /*  if the current interval is included in  */
  8. /*  the query interval return segTree[node]  */
  9. if (begin >= left && end <= right)
  10. return segTree[node];
  11. /*  compute the minimum position in the  */
  12. /*  left and right part of the interval  */
  13. p1 = query(2 * node, begin, (begin + end) / 2, left, right);
  14. p2 = query(2 * node + 1, (begin + end) / 2 + 1, end, left, right);
  15. /*  return the expect value  */
  16. if (p1 == -1)
  17. return p2;
  18. if (p2 == -1)
  19. return p1;
  20. if (p1 <= p2)
  21. return  p1;
  22. return  p2;
  23. }
int query(int node, int begin, int end, int left, int right)
{
    int p1, p2;  

    /*  查询区间和要求的区间没有交集  */
    if (left > end || right < begin)
        return -1;  

    /*  if the current interval is included in  */
    /*  the query interval return segTree[node]  */
    if (begin >= left && end <= right)
        return segTree[node];  

    /*  compute the minimum position in the  */
    /*  left and right part of the interval  */
    p1 = query(2 * node, begin, (begin + end) / 2, left, right);
    p2 = query(2 * node + 1, (begin + end) / 2 + 1, end, left, right);  

    /*  return the expect value  */
    if (p1 == -1)
        return p2;
    if (p2 == -1)
        return p1;
    if (p1 <= p2)
        return  p1;
    return  p2;
} 

int node, int begin, int end, int ind, int add)/*单节点更新*/

  • {
  • if( begin == end )
  • {
  • segTree[node] += add;
  • return ;
  • }
  • int m = ( left + right ) >> 1;
  • if(ind <= m)
  • Updata(node * 2,left, m, ind, add);
  • else
  • Updata(node * 2 + 1, m + 1, right, ind, add);
  • /*回溯更新父节点*/
  • segTree[node] = min(segTree[node * 2], segTree[node * 2 + 1]);
  • }
void Updata(int node, int begin, int end, int ind, int add)/*单节点更新*/
{  

    if( begin == end )
    {
        segTree[node] += add;
        return ;
    }
    int m = ( left + right ) >> 1;
    if(ind <= m)
        Updata(node * 2,left, m, ind, add);
    else
        Updata(node * 2 + 1, m + 1, right, ind, add);
    /*回溯更新父节点*/
    segTree[node] = min(segTree[node * 2], segTree[node * 2 + 1]);   

} 

b:区间更新(线段树中最有用的)

需要用到延迟标记,每个结点新增加一个标记,记录这个结点是否被进行了某种修改操作(这种修改操作会影响其子结点)。对于任意区间的修改,我们先按照查询的方式将其划分成线段树中的结点,然后修改这些结点的信息,并给这些结点标上代表这种修改操作的标记。在修改和查询的时候,如果我们到了一个结点p,并且决定考虑其子结点,那么我们就要看看结点p有没有标记,如果有,就要按照标记修改其子结点的信息,并且给子结点都标上相同的标记,同时消掉p的标记。(优点在于,不用将区间内的所有值都暴力更新,大大提高效率,因此区间更新是最优用的操作)

void Change来自dongxicheng.org

[cpp] view plaincopyprint?

  1. void Change(node *p, int a, int b) /* 当前考察结点为p,修改区间为(a,b]*/
  2. {
  3. if (a <= p->Left && p->Right <= b)
  4. /* 如果当前结点的区间包含在修改区间内*/
  5. {
  6. ...... /* 修改当前结点的信息,并标上标记*/
  7. return;
  8. }
  9. Push_Down(p); /* 把当前结点的标记向下传递*/
  10. int mid = (p->Left + p->Right) / 2; /* 计算左右子结点的分隔点
  11. if (a < mid) Change(p->Lch, a, b); /* 和左孩子有交集,考察左子结点*/
  12. if (b > mid) Change(p->Rch, a, b); /* 和右孩子有交集,考察右子结点*/
  13. Update(p); /* 维护当前结点的信息(因为其子结点的信息可能有更改)*/
  14. }
void Change(node *p, int a, int b) /* 当前考察结点为p,修改区间为(a,b]*/

{

  if (a <= p->Left && p->Right <= b)

  /* 如果当前结点的区间包含在修改区间内*/

  {

     ...... /* 修改当前结点的信息,并标上标记*/

     return;

  }

  Push_Down(p); /* 把当前结点的标记向下传递*/

  int mid = (p->Left + p->Right) / 2; /* 计算左右子结点的分隔点

  if (a < mid) Change(p->Lch, a, b); /* 和左孩子有交集,考察左子结点*/

  if (b > mid) Change(p->Rch, a, b); /* 和右孩子有交集,考察右子结点*/

  Update(p); /* 维护当前结点的信息(因为其子结点的信息可能有更改)*/

}

3:主要应用

(1):区间最值查询问题 (见模板1)

(2):连续区间修改或者单节点更新的动态查询问题 (见模板2)

(3):多维空间的动态查询 (见模板3)

 

二:典型模板

模板1:

RMQ,查询区间最值下标---min

[cpp] view plaincopyprint?

  1. #include<iostream>
  2. using namespace std;
  3. #define MAXN 100
  4. #define MAXIND 256 //线段树节点个数
  5. //构建线段树,目的:得到M数组.
  6. void build(int node, int b, int e, int M[], int A[])
  7. {
  8. if (b == e)
  9. M[node] = b; //只有一个元素,只有一个下标
  10. else
  11. {
  12. build(2 * node, b, (b + e) / 2, M, A);
  13. build(2 * node + 1, (b + e) / 2 + 1, e, M, A);
  14. if (A[M[2 * node]] <= A[M[2 * node + 1]])
  15. M[node] = M[2 * node];
  16. else
  17. M[node] = M[2 * node + 1];
  18. }
  19. }
  20. //找出区间 [i, j] 上的最小值的索引
  21. int query(int node, int b, int e, int M[], int A[], int i, int j)
  22. {
  23. int p1, p2;
  24. //查询区间和要求的区间没有交集
  25. if (i > e || j < b)
  26. return -1;
  27. if (b >= i && e <= j)
  28. return M[node];
  29. p1 = query(2 * node, b, (b + e) / 2, M, A, i, j);
  30. p2 = query(2 * node + 1, (b + e) / 2 + 1, e, M, A, i, j);
  31. //return the position where the overall
  32. //minimum is
  33. if (p1 == -1)
  34. return M[node] = p2;
  35. if (p2 == -1)
  36. return M[node] = p1;
  37. if (A[p1] <= A[p2])
  38. return M[node] = p1;
  39. return M[node] = p2;
  40. }
  41. int main()
  42. {
  43. int M[MAXIND]; //下标1起才有意义,否则不是二叉树,保存下标编号节点对应区间最小值的下标.
  44. memset(M,-1,sizeof(M));
  45. int a[]={3,4,5,7,2,1,0,3,4,5};
  46. build(1, 0, sizeof(a)/sizeof(a[0])-1, M, a);
  47. cout<<query(1, 0, sizeof(a)/sizeof(a[0])-1, M, a, 0, 5)<<endl;
  48. return 0;
  49. }
#include<iostream>  

using namespace std;  

#define MAXN 100
#define MAXIND 256 //线段树节点个数  

//构建线段树,目的:得到M数组.
void build(int node, int b, int e, int M[], int A[])
{
    if (b == e)
        M[node] = b; //只有一个元素,只有一个下标
    else
    {
        build(2 * node, b, (b + e) / 2, M, A);
        build(2 * node + 1, (b + e) / 2 + 1, e, M, A);  

	    if (A[M[2 * node]] <= A[M[2 * node + 1]])
	        M[node] = M[2 * node];
	    else
	        M[node] = M[2 * node + 1];
    }
}  

//找出区间 [i, j] 上的最小值的索引
int query(int node, int b, int e, int M[], int A[], int i, int j)
{
    int p1, p2;  

    //查询区间和要求的区间没有交集
    if (i > e || j < b)
        return -1;  

    if (b >= i && e <= j)
        return M[node];  

    p1 = query(2 * node, b, (b + e) / 2, M, A, i, j);
    p2 = query(2 * node + 1, (b + e) / 2 + 1, e, M, A, i, j);  

    //return the position where the overall
    //minimum is
    if (p1 == -1)
        return M[node] = p2;
    if (p2 == -1)
        return M[node] = p1;
    if (A[p1] <= A[p2])
        return M[node] = p1;
    return M[node] = p2;  

}  

int main()
{
    int M[MAXIND]; //下标1起才有意义,否则不是二叉树,保存下标编号节点对应区间最小值的下标.
    memset(M,-1,sizeof(M));
    int a[]={3,4,5,7,2,1,0,3,4,5};
    build(1, 0, sizeof(a)/sizeof(a[0])-1, M, a);
    cout<<query(1, 0, sizeof(a)/sizeof(a[0])-1, M, a, 0, 5)<<endl;
    return 0;
}

模板2:

连续区间修改或者单节点更新的动态查询问题 (此模板查询区间和)

[cpp] view plaincopyprint?

  1. #include <cstdio>
  2. #include <algorithm>
  3. using namespace std;
  4. #define lson l , m , rt << 1
  5. #define rson m + 1 , r , rt << 1 | 1
  6. #define root 1 , N , 1
  7. #define LL long long
  8. const int maxn = 111111;
  9. LL add[maxn<<2];
  10. LL sum[maxn<<2];
  11. void PushUp(int rt) {
  12. sum[rt] = sum[rt<<1] + sum[rt<<1|1];
  13. }
  14. void PushDown(int rt,int m) {
  15. if (add[rt]) {
  16. add[rt<<1] += add[rt];
  17. add[rt<<1|1] += add[rt];
  18. sum[rt<<1] += add[rt] * (m - (m >> 1));
  19. sum[rt<<1|1] += add[rt] * (m >> 1);
  20. add[rt] = 0;
  21. }
  22. }
  23. void build(int l,int r,int rt) {
  24. add[rt] = 0;
  25. if (l == r) {
  26. scanf("%lld",&sum[rt]);
  27. return ;
  28. }
  29. int m = (l + r) >> 1;
  30. build(lson);
  31. build(rson);
  32. PushUp(rt);
  33. }
  34. void update(int L,int R,int c,int l,int r,int rt) {
  35. if (L <= l && r <= R) {
  36. add[rt] += c;
  37. sum[rt] += (LL)c * (r - l + 1);
  38. return ;
  39. }
  40. PushDown(rt , r - l + 1);
  41. int m = (l + r) >> 1;
  42. if (L <= m) update(L , R , c , lson);
  43. if (m < R) update(L , R , c , rson);
  44. PushUp(rt);
  45. }
  46. LL query(int L,int R,int l,int r,int rt) {
  47. if (L <= l && r <= R) {
  48. return sum[rt];
  49. }
  50. PushDown(rt , r - l + 1);
  51. int m = (l + r) >> 1;
  52. LL ret = 0;
  53. if (L <= m) ret += query(L , R , lson);
  54. if (m < R) ret += query(L , R , rson);
  55. return ret;
  56. }
  57. int main() {
  58. int N , Q;
  59. scanf("%d%d",&N,&Q);
  60. build(root);
  61. while (Q --) {
  62. char op[2];
  63. int a , b , c;
  64. scanf("%s",op);
  65. if (op[0] == ‘Q‘) {
  66. scanf("%d%d",&a,&b);
  67. printf("%lld\n",query(a , b ,root));
  68. } else {
  69. scanf("%d%d%d",&a,&b,&c);
  70. update(a , b , c , root);
  71. }
  72. }
  73. return 0;
  74. }
#include <cstdio>
#include <algorithm>
using namespace std;  

#define lson l , m , rt << 1
#define rson m + 1 , r , rt << 1 | 1
#define root 1 , N , 1
#define LL long long
const int maxn = 111111;
LL add[maxn<<2];
LL sum[maxn<<2];
void PushUp(int rt) {
    sum[rt] = sum[rt<<1] + sum[rt<<1|1];
}
void PushDown(int rt,int m) {
    if (add[rt]) {
        add[rt<<1] += add[rt];
        add[rt<<1|1] += add[rt];
        sum[rt<<1] += add[rt] * (m - (m >> 1));
        sum[rt<<1|1] += add[rt] * (m >> 1);
        add[rt] = 0;
    }
}
void build(int l,int r,int rt) {
    add[rt] = 0;
    if (l == r) {
        scanf("%lld",&sum[rt]);
        return ;
    }
    int m = (l + r) >> 1;
    build(lson);
    build(rson);
    PushUp(rt);
}
void update(int L,int R,int c,int l,int r,int rt) {
    if (L <= l && r <= R) {
        add[rt] += c;
        sum[rt] += (LL)c * (r - l + 1);
        return ;
    }
    PushDown(rt , r - l + 1);
    int m = (l + r) >> 1;
    if (L <= m) update(L , R , c , lson);
    if (m < R) update(L , R , c , rson);
    PushUp(rt);
}
LL query(int L,int R,int l,int r,int rt) {
    if (L <= l && r <= R) {
        return sum[rt];
    }
    PushDown(rt , r - l + 1);
    int m = (l + r) >> 1;
    LL ret = 0;
    if (L <= m) ret += query(L , R , lson);
    if (m < R) ret += query(L , R , rson);
    return ret;
}
int main() {
    int N , Q;
    scanf("%d%d",&N,&Q);
    build(root);
    while (Q --) {
        char op[2];
        int a , b , c;
        scanf("%s",op);
        if (op[0] == ‘Q‘) {
            scanf("%d%d",&a,&b);
            printf("%lld\n",query(a , b ,root));
        } else {
            scanf("%d%d%d",&a,&b,&c);
            update(a , b , c , root);
        }
    }
    return 0;
}  

模板3:

多维空间的动态查询

三:练习题目

下面是hh线段树代码,典型练习哇~

在代码前先介绍一些我的线段树风格:

  • maxn是题目给的最大区间,而节点数要开4倍,确切的来说节点数要开大于maxn的最小2x的两倍
  • lson和rson分辨表示结点的左儿子和右儿子,由于每次传参数的时候都固定是这几个变量,所以可以用预定于比较方便的表示
  • 以前的写法是另外开两个个数组记录每个结点所表示的区间,其实这个区间不必保存,一边算一边传下去就行,只需要写函数的时候多两个参数,结合lson和rson的预定义可以很方便
  • PushUP(int rt)是把当前结点的信息更新到父结点
  • PushDown(int rt)是把当前结点的信息更新给儿子结点
  • rt表示当前子树的根(root),也就是当前所在的结点

整理这些题目后我觉得线段树的题目整体上可以分成以下四个部分:

单点更新:最最基础的线段树,只更新叶子节点,然后把信息用PushUP(int r)这个函数更新上来

 

  • hdu1166 敌兵布阵
  • 题意:O(-1)
  • 思路:O(-1)
    线段树功能:update:单点增减 query:区间求和

code:

[cpp] view plaincopyprint?

  1. #include<cstring>
  2. #include<iostream>
  3. #define M 50005
  4. #define lson l,m,rt<<1
  5. #define rson m+1,r,rt<<1|1
  6. /*left,right,root,middle*/
  7. int sum[M<<2];
  8. inline void PushPlus(int rt)
  9. {
  10. sum[rt] = sum[rt<<1] + sum[rt<<1|1];
  11. }
  12. void Build(int l, int r, int rt)
  13. {
  14. if(l == r)
  15. {
  16. scanf("%d", &sum[rt]);
  17. return ;
  18. }
  19. int m = ( l + r )>>1;
  20. Build(lson);
  21. Build(rson);
  22. PushPlus(rt);
  23. }
  24. void Updata(int p, int add, int l, int r, int rt)
  25. {
  26. if( l == r )
  27. {
  28. sum[rt] += add;
  29. return ;
  30. }
  31. int m = ( l + r ) >> 1;
  32. if(p <= m)
  33. Updata(p, add, lson);
  34. else
  35. Updata(p, add, rson);
  36. PushPlus(rt);
  37. }
  38. int Query(int L,int R,int l,int r,int rt)
  39. {
  40. if( L <= l && r <= R )
  41. {
  42. return sum[rt];
  43. }
  44. int m = ( l + r ) >> 1;
  45. int ans=0;
  46. if(L<=m )
  47. ans+=Query(L,R,lson);
  48. if(R>m)
  49. ans+=Query(L,R,rson);
  50. return ans;
  51. }
  52. int main()
  53. {
  54. int T, n, a, b;
  55. scanf("%d",&T);
  56. for( int i = 1; i <= T; ++i )
  57. {
  58. printf("Case %d:\n",i);
  59. scanf("%d",&n);
  60. Build(1,n,1);
  61. char op[10];
  62. while( scanf("%s",op) &&op[0]!=‘E‘ )
  63. {
  64. scanf("%d %d", &a, &b);
  65. if(op[0] == ‘Q‘)
  66. printf("%d\n",Query(a,b,1,n,1));
  67. else if(op[0] == ‘S‘)
  68. Updata(a,-b,1,n,1);
  69. else
  70. Updata(a,b,1,n,1);
  71. }
  72. }
  73. return 0;
  74. }
#include<cstring>
#include<iostream>

#define M 50005
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
/*left,right,root,middle*/

int sum[M<<2];

inline void PushPlus(int rt)
{
	sum[rt] = sum[rt<<1] + sum[rt<<1|1];
}

void Build(int l, int r, int rt)
{
	if(l == r)
	{
		scanf("%d", &sum[rt]);
		return ;
	}
	int m = ( l + r )>>1;

	Build(lson);
	Build(rson);
	PushPlus(rt);
}

void Updata(int p, int add, int l, int r, int rt)
{

	if( l == r )
	{
		sum[rt] += add;
		return ;
	}
	int m = ( l + r ) >> 1;
	if(p <= m)
		Updata(p, add, lson);
	else
		Updata(p, add, rson);

	PushPlus(rt);
}

int Query(int L,int R,int l,int r,int rt)
{
	if( L <= l && r <= R )
	{
		return sum[rt];
	}
	int m = ( l + r ) >> 1;
	int ans=0;
	if(L<=m )
		ans+=Query(L,R,lson);
	if(R>m)
		ans+=Query(L,R,rson);

	return ans;
}
int main()
{
	int T, n, a, b;
	scanf("%d",&T);
	for( int i = 1; i <= T; ++i )
	{
		printf("Case %d:\n",i);
		scanf("%d",&n);
		Build(1,n,1);

		char op[10];

		while( scanf("%s",op) &&op[0]!=‘E‘ )
		{

			scanf("%d %d", &a, &b);
			if(op[0] == ‘Q‘)
				printf("%d\n",Query(a,b,1,n,1));
			else if(op[0] == ‘S‘)
				Updata(a,-b,1,n,1);
			else
				Updata(a,b,1,n,1);

		}
	}
	return 0;
}

hdu1754 I Hate It题意:O(-1)
思路:O(-1)
线段树功能:update:单点替换 query:区间最值

[cpp] view plaincopyprint?

  1. #include <cstdio>
  2. #include <algorithm>
  3. using namespace std;
  4. #define lson l , m , rt << 1
  5. #define rson m + 1 , r , rt << 1 | 1
  6. const int maxn = 222222;
  7. int MAX[maxn<<2];
  8. void PushUP(int rt) {
  9. MAX[rt] = max(MAX[rt<<1] , MAX[rt<<1|1]);
  10. }
  11. void build(int l,int r,int rt) {
  12. if (l == r) {
  13. scanf("%d",&MAX[rt]);
  14. return ;
  15. }
  16. int m = (l + r) >> 1;
  17. build(lson);
  18. build(rson);
  19. PushUP(rt);
  20. }
  21. void update(int p,int sc,int l,int r,int rt) {
  22. if (l == r) {
  23. MAX[rt] = sc;
  24. return ;
  25. }
  26. int m = (l + r) >> 1;
  27. if (p <= m) update(p , sc , lson);
  28. else update(p , sc , rson);
  29. PushUP(rt);
  30. }
  31. int query(int L,int R,int l,int r,int rt) {
  32. if (L <= l && r <= R) {
  33. return MAX[rt];
  34. }
  35. int m = (l + r) >> 1;
  36. int ret = 0;
  37. if (L <= m) ret = max(ret , query(L , R , lson));
  38. if (R > m) ret = max(ret , query(L , R , rson));
  39. return ret;
  40. }
  41. int main() {
  42. int n , m;
  43. while (~scanf("%d%d",&n,&m)) {
  44. build(1 , n , 1);
  45. while (m --) {
  46. char op[2];
  47. int a , b;
  48. scanf("%s%d%d",op,&a,&b);
  49. if (op[0] == ‘Q‘) printf("%d\n",query(a , b , 1 , n , 1));
  50. else update(a , b , 1 , n , 1);
  51. }
  52. }
  53. return 0;
  54. }
#include <cstdio>
#include <algorithm>
using namespace std;

#define lson l , m , rt << 1
#define rson m + 1 , r , rt << 1 | 1
const int maxn = 222222;
int MAX[maxn<<2];
void PushUP(int rt) {
	MAX[rt] = max(MAX[rt<<1] , MAX[rt<<1|1]);
}
void build(int l,int r,int rt) {
	if (l == r) {
		scanf("%d",&MAX[rt]);
		return ;
	}
	int m = (l + r) >> 1;
	build(lson);
	build(rson);
	PushUP(rt);
}
void update(int p,int sc,int l,int r,int rt) {
	if (l == r) {
		MAX[rt] = sc;
		return ;
	}
	int m = (l + r) >> 1;
	if (p <= m) update(p , sc , lson);
	else update(p , sc , rson);
	PushUP(rt);
}
int query(int L,int R,int l,int r,int rt) {
	if (L <= l && r <= R) {
		return MAX[rt];
	}
	int m = (l + r) >> 1;
	int ret = 0;
	if (L <= m) ret = max(ret , query(L , R , lson));
	if (R > m) ret = max(ret , query(L , R , rson));
	return ret;
}
int main() {
	int n , m;
	while (~scanf("%d%d",&n,&m)) {
		build(1 , n , 1);
		while (m --) {
			char op[2];
			int a , b;
			scanf("%s%d%d",op,&a,&b);
			if (op[0] == ‘Q‘) printf("%d\n",query(a , b , 1 , n , 1));
			else update(a , b , 1 , n , 1);
		}
	}
	return 0;
}

hdu1394 Minimum Inversion Number
题意:求Inversion后的最小逆序数
思路:用O(nlogn)复杂度求出最初逆序数后,就可以用O(1)的复杂度分别递推出其他解
线段树功能:update:单点增减 query:区间求和

[cpp] view plaincopyprint?

  1. #include <cstdio>
  2. #include <algorithm>
  3. using namespace std;
  4. #define lson l , m , rt << 1
  5. #define rson m + 1 , r , rt << 1 | 1
  6. const int maxn = 5555;
  7. int sum[maxn<<2];
  8. void PushUP(int rt) {
  9. sum[rt] = sum[rt<<1] + sum[rt<<1|1];
  10. }
  11. void build(int l,int r,int rt) {
  12. sum[rt] = 0;
  13. if (l == r) return ;
  14. int m = (l + r) >> 1;
  15. build(lson);
  16. build(rson);
  17. }
  18. void update(int p,int l,int r,int rt) {
  19. if (l == r) {
  20. sum[rt] ++;
  21. return ;
  22. }
  23. int m = (l + r) >> 1;
  24. if (p <= m) update(p , lson);
  25. else update(p , rson);
  26. PushUP(rt);
  27. }
  28. int query(int L,int R,int l,int r,int rt) {
  29. if (L <= l && r <= R) {
  30. return sum[rt];
  31. }
  32. int m = (l + r) >> 1;
  33. int ret = 0;
  34. if (L <= m) ret += query(L , R , lson);
  35. if (R > m) ret += query(L , R , rson);
  36. return ret;
  37. }
  38. int x[maxn];
  39. int main() {
  40. int n;
  41. while (~scanf("%d",&n)) {
  42. build(0 , n - 1 , 1);
  43. int sum = 0;
  44. for (int i = 0 ; i < n ; i ++) {
  45. scanf("%d",&x[i]);
  46. sum += query(x[i] , n - 1 , 0 , n - 1 , 1);
  47. update(x[i] , 0 , n - 1 , 1);
  48. }
  49. int ret = sum;
  50. for (int i = 0 ; i < n ; i ++) {
  51. sum += n - x[i] - x[i] - 1;
  52. ret = min(ret , sum);
  53. }
  54. printf("%d\n",ret);
  55. }
  56. return 0;
  57. }
#include <cstdio>
#include <algorithm>
using namespace std;

#define lson l , m , rt << 1
#define rson m + 1 , r , rt << 1 | 1
const int maxn = 5555;
int sum[maxn<<2];
void PushUP(int rt) {
	sum[rt] = sum[rt<<1] + sum[rt<<1|1];
}
void build(int l,int r,int rt) {
	sum[rt] = 0;
	if (l == r) return ;
	int m = (l + r) >> 1;
	build(lson);
	build(rson);
}
void update(int p,int l,int r,int rt) {
	if (l == r) {
		sum[rt] ++;
		return ;
	}
	int m = (l + r) >> 1;
	if (p <= m) update(p , lson);
	else update(p , rson);
	PushUP(rt);
}
int query(int L,int R,int l,int r,int rt) {
	if (L <= l && r <= R) {
		return sum[rt];
	}
	int m = (l + r) >> 1;
	int ret = 0;
	if (L <= m) ret += query(L , R , lson);
	if (R > m) ret += query(L , R , rson);
	return ret;
}
int x[maxn];
int main() {
	int n;
	while (~scanf("%d",&n)) {
		build(0 , n - 1 , 1);
		int sum = 0;
		for (int i = 0 ; i < n ; i ++) {
			scanf("%d",&x[i]);
			sum += query(x[i] , n - 1 , 0 , n - 1 , 1);
			update(x[i] , 0 , n - 1 , 1);
		}
		int ret = sum;
		for (int i = 0 ; i < n ; i ++) {
			sum += n - x[i] - x[i] - 1;
			ret = min(ret , sum);
		}
		printf("%d\n",ret);
	}
	return 0;
}

hdu2795 Billboard
题意:h*w的木板,放进一些1*L的物品,求每次放空间能容纳且最上边的位子
思路:每次找到最大值的位子,然后减去L
线段树功能:query:区间求最大值的位子(直接把update的操作在query里做了)

[cpp] view plaincopyprint?

  1. #include <cstdio>
  2. #include <algorithm>
  3. using namespace std;
  4. #define lson l , m , rt << 1
  5. #define rson m + 1 , r , rt << 1 | 1
  6. const int maxn = 222222;
  7. int h , w , n;
  8. int MAX[maxn<<2];
  9. void PushUP(int rt) {
  10. MAX[rt] = max(MAX[rt<<1] , MAX[rt<<1|1]);
  11. }
  12. void build(int l,int r,int rt) {
  13. MAX[rt] = w;
  14. if (l == r) return ;
  15. int m = (l + r) >> 1;
  16. build(lson);
  17. build(rson);
  18. }
  19. int query(int x,int l,int r,int rt) {
  20. if (l == r) {
  21. MAX[rt] -= x;
  22. return l;
  23. }
  24. int m = (l + r) >> 1;
  25. int ret = (MAX[rt<<1] >= x) ? query(x , lson) : query(x , rson);
  26. PushUP(rt);
  27. return ret;
  28. }
  29. int main() {
  30. while (~scanf("%d%d%d",&h,&w,&n)) {
  31. if (h > n) h = n;
  32. build(1 , h , 1);
  33. while (n --) {
  34. int x;
  35. scanf("%d",&x);
  36. if (MAX[1] < x) puts("-1");
  37. else printf("%d\n",query(x , 1 , h , 1));
  38. }
  39. }
  40. return 0;
  41. }
#include <cstdio>
#include <algorithm>
using namespace std;

#define lson l , m , rt << 1
#define rson m + 1 , r , rt << 1 | 1
const int maxn = 222222;
int h , w , n;
int MAX[maxn<<2];
void PushUP(int rt) {
	MAX[rt] = max(MAX[rt<<1] , MAX[rt<<1|1]);
}
void build(int l,int r,int rt) {
	MAX[rt] = w;
	if (l == r) return ;
	int m = (l + r) >> 1;
	build(lson);
	build(rson);
}
int query(int x,int l,int r,int rt) {
	if (l == r) {
		MAX[rt] -= x;
		return l;
	}
	int m = (l + r) >> 1;
	int ret = (MAX[rt<<1] >= x) ? query(x , lson) : query(x , rson);
	PushUP(rt);
	return ret;
}
int main() {
	while (~scanf("%d%d%d",&h,&w,&n)) {
		if (h > n) h = n;
		build(1 , h , 1);
		while (n --) {
			int x;
			scanf("%d",&x);
			if (MAX[1] < x) puts("-1");
			else printf("%d\n",query(x , 1 , h , 1));
		}
	}
	return 0;
}

成段更新(通常这对初学者来说是一道坎),需要用到延迟标记(或者说懒惰标记),简单来说就是每次更新的时候不要更新到底,用延迟标记使得更新延迟到下次需要更新or询问到的时候

hdu1698 Just a Hook
题意:O(-1)
思路:O(-1)
线段树功能:update:成段替换 (由于只query一次总区间,所以可以直接输出1结点的信息)

[cpp] view plaincopyprint?

  1. #include <cstdio>
  2. #include <algorithm>
  3. using namespace std;
  4. #define lson l , m , rt << 1
  5. #define rson m + 1 , r , rt << 1 | 1
  6. const int maxn = 111111;
  7. int h , w , n;
  8. int col[maxn<<2];
  9. int sum[maxn<<2];
  10. void PushUp(int rt) {
  11. sum[rt] = sum[rt<<1] + sum[rt<<1|1];
  12. }
  13. void PushDown(int rt,int m) {
  14. if (col[rt]) {
  15. col[rt<<1] = col[rt<<1|1] = col[rt];
  16. sum[rt<<1] = (m - (m >> 1)) * col[rt];
  17. sum[rt<<1|1] = (m >> 1) * col[rt];
  18. col[rt] = 0;
  19. }
  20. }
  21. void build(int l,int r,int rt) {
  22. col[rt] = 0;
  23. sum[rt] = 1;
  24. if (l == r) return ;
  25. int m = (l + r) >> 1;
  26. build(lson);
  27. build(rson);
  28. PushUp(rt);
  29. }
  30. void update(int L,int R,int c,int l,int r,int rt) {
  31. if (L <= l && r <= R) {
  32. col[rt] = c;
  33. sum[rt] = c * (r - l + 1);
  34. return ;
  35. }
  36. PushDown(rt , r - l + 1);
  37. int m = (l + r) >> 1;
  38. if (L <= m) update(L , R , c , lson);
  39. if (R > m) update(L , R , c , rson);
  40. PushUp(rt);
  41. }
  42. int main() {
  43. int T , n , m;
  44. scanf("%d",&T);
  45. for (int cas = 1 ; cas <= T ; cas ++) {
  46. scanf("%d%d",&n,&m);
  47. build(1 , n , 1);
  48. while (m --) {
  49. int a , b , c;
  50. scanf("%d%d%d",&a,&b,&c);
  51. update(a , b , c , 1 , n , 1);
  52. }
  53. printf("Case %d: The total value of the hook is %d.\n",cas , sum[1]);
  54. }
  55. return 0;
  56. }
#include <cstdio>
#include <algorithm>
using namespace std;

#define lson l , m , rt << 1
#define rson m + 1 , r , rt << 1 | 1
const int maxn = 111111;
int h , w , n;
int col[maxn<<2];
int sum[maxn<<2];
void PushUp(int rt) {
	sum[rt] = sum[rt<<1] + sum[rt<<1|1];
}
void PushDown(int rt,int m) {
	if (col[rt]) {
		col[rt<<1] = col[rt<<1|1] = col[rt];
		sum[rt<<1] = (m - (m >> 1)) * col[rt];
		sum[rt<<1|1] = (m >> 1) * col[rt];
		col[rt] = 0;
	}
}
void build(int l,int r,int rt) {
	col[rt] = 0;
	sum[rt] = 1;
	if (l == r) return ;
	int m = (l + r) >> 1;
	build(lson);
	build(rson);
	PushUp(rt);
}
void update(int L,int R,int c,int l,int r,int rt) {
	if (L <= l && r <= R) {
		col[rt] = c;
		sum[rt] = c * (r - l + 1);
		return ;
	}
	PushDown(rt , r - l + 1);
	int m = (l + r) >> 1;
	if (L <= m) update(L , R , c , lson);
	if (R > m) update(L , R , c , rson);
	PushUp(rt);
}
int main() {
	int T , n , m;
	scanf("%d",&T);
	for (int cas = 1 ; cas <= T ; cas ++) {
		scanf("%d%d",&n,&m);
		build(1 , n , 1);
		while (m --) {
			int a , b , c;
			scanf("%d%d%d",&a,&b,&c);
			update(a , b , c , 1 , n , 1);
		}
		printf("Case %d: The total value of the hook is %d.\n",cas , sum[1]);
	}
	return 0;
}

poj3468 A Simple Problem with Integers
题意:O(-1)
思路:O(-1)
线段树功能:update:成段增减 query:区间求和

[cpp] view plaincopyprint?

  1. #include <cstdio>
  2. #include <algorithm>
  3. using namespace std;
  4. #define lson l , m , rt << 1
  5. #define rson m + 1 , r , rt << 1 | 1
  6. #define LL long long
  7. const int maxn = 111111;
  8. LL add[maxn<<2];
  9. LL sum[maxn<<2];
  10. void PushUp(int rt) {
  11. sum[rt] = sum[rt<<1] + sum[rt<<1|1];
  12. }
  13. void PushDown(int rt,int m) {
  14. if (add[rt]) {
  15. add[rt<<1] += add[rt];
  16. add[rt<<1|1] += add[rt];
  17. sum[rt<<1] += add[rt] * (m - (m >> 1));
  18. sum[rt<<1|1] += add[rt] * (m >> 1);
  19. add[rt] = 0;
  20. }
  21. }
  22. void build(int l,int r,int rt) {
  23. add[rt] = 0;
  24. if (l == r) {
  25. scanf("%lld",&sum[rt]);
  26. return ;
  27. }
  28. int m = (l + r) >> 1;
  29. build(lson);
  30. build(rson);
  31. PushUp(rt);
  32. }
  33. void update(int L,int R,int c,int l,int r,int rt) {
  34. if (L <= l && r <= R) {
  35. add[rt] += c;
  36. sum[rt] += (LL)c * (r - l + 1);
  37. return ;
  38. }
  39. PushDown(rt , r - l + 1);
  40. int m = (l + r) >> 1;
  41. if (L <= m) update(L , R , c , lson);
  42. if (m < R) update(L , R , c , rson);
  43. PushUp(rt);
  44. }
  45. LL query(int L,int R,int l,int r,int rt) {
  46. if (L <= l && r <= R) {
  47. return sum[rt];
  48. }
  49. PushDown(rt , r - l + 1);
  50. int m = (l + r) >> 1;
  51. LL ret = 0;
  52. if (L <= m) ret += query(L , R , lson);
  53. if (m < R) ret += query(L , R , rson);
  54. return ret;
  55. }
  56. int main() {
  57. int N , Q;
  58. scanf("%d%d",&N,&Q);
  59. build(1 , N , 1);
  60. while (Q --) {
  61. char op[2];
  62. int a , b , c;
  63. scanf("%s",op);
  64. if (op[0] == ‘Q‘) {
  65. scanf("%d%d",&a,&b);
  66. printf("%lld\n",query(a , b , 1 , N , 1));
  67. } else {
  68. scanf("%d%d%d",&a,&b,&c);
  69. update(a , b , c , 1 , N , 1);
  70. }
  71. }
  72. return 0;
  73. }
#include <cstdio>
#include <algorithm>
using namespace std;

#define lson l , m , rt << 1
#define rson m + 1 , r , rt << 1 | 1
#define LL long long
const int maxn = 111111;
LL add[maxn<<2];
LL sum[maxn<<2];
void PushUp(int rt) {
	sum[rt] = sum[rt<<1] + sum[rt<<1|1];
}
void PushDown(int rt,int m) {
	if (add[rt]) {
		add[rt<<1] += add[rt];
		add[rt<<1|1] += add[rt];
		sum[rt<<1] += add[rt] * (m - (m >> 1));
		sum[rt<<1|1] += add[rt] * (m >> 1);
		add[rt] = 0;
	}
}
void build(int l,int r,int rt) {
	add[rt] = 0;
	if (l == r) {
		scanf("%lld",&sum[rt]);
		return ;
	}
	int m = (l + r) >> 1;
	build(lson);
	build(rson);
	PushUp(rt);
}
void update(int L,int R,int c,int l,int r,int rt) {
	if (L <= l && r <= R) {
		add[rt] += c;
		sum[rt] += (LL)c * (r - l + 1);
		return ;
	}
	PushDown(rt , r - l + 1);
	int m = (l + r) >> 1;
	if (L <= m) update(L , R , c , lson);
	if (m < R) update(L , R , c , rson);
	PushUp(rt);
}
LL query(int L,int R,int l,int r,int rt) {
	if (L <= l && r <= R) {
		return sum[rt];
	}
	PushDown(rt , r - l + 1);
	int m = (l + r) >> 1;
	LL ret = 0;
	if (L <= m) ret += query(L , R , lson);
	if (m < R) ret += query(L , R , rson);
	return ret;
}
int main() {
	int N , Q;
	scanf("%d%d",&N,&Q);
	build(1 , N , 1);
	while (Q --) {
		char op[2];
		int a , b , c;
		scanf("%s",op);
		if (op[0] == ‘Q‘) {
			scanf("%d%d",&a,&b);
			printf("%lld\n",query(a , b , 1 , N , 1));
		} else {
			scanf("%d%d%d",&a,&b,&c);
			update(a , b , c , 1 , N , 1);
		}
	}
	return 0;
}

poj2528 Mayor’s posters
题意:在墙上贴海报,海报可以互相覆盖,问最后可以看见几张海报
思路:这题数据范围很大,直接搞超时+超内存,需要离散化:
离散化简单的来说就是只取我们需要的值来用,比如说区间[1000,2000],[1990,2012] 我们用不到[-∞,999][1001,1989][1991,1999][2001,2011][2013,+∞]这些值,所以我只需要1000,1990,2000,2012就够了,将其分别映射到0,1,2,3,在于复杂度就大大的降下来了
所以离散化要保存所有需要用到的值,排序后,分别映射到1~n,这样复杂度就会小很多很多
而这题的难点在于每个数字其实表示的是一个单位长度(并非一个点),这样普通的离散化会造成许多错误(包括我以前的代码,poj这题数据奇弱)
给出下面两个简单的例子应该能体现普通离散化的缺陷:
例子一:1-10 1-4 5-10
例子二:1-10 1-4 6-10
普通离散化后都变成了[1,4][1,2][3,4]
线段2覆盖了[1,2],线段3覆盖了[3,4],那么线段1是否被完全覆盖掉了呢?
例子一是完全被覆盖掉了,而例子二没有被覆盖

为了解决这种缺陷,我们可以在排序后的数组上加些处理,比如说[1,2,6,10]
如果相邻数字间距大于1的话,在其中加上任意一个数字,比如加成[1,2,3,6,7,10],然后再做线段树就好了.
线段树功能:update:成段替换 query:简单hash

[cpp] view plaincopyprint?

  1. #include <cstdio>
  2. #include <cstring>
  3. #include <algorithm>
  4. using namespace std;
  5. #define lson l , m , rt << 1
  6. #define rson m + 1 , r , rt << 1 | 1
  7. const int maxn = 11111;
  8. bool hash[maxn];
  9. int li[maxn] , ri[maxn];
  10. int X[maxn*3];
  11. int col[maxn<<4];
  12. int cnt;
  13. void PushDown(int rt) {
  14. if (col[rt] != -1) {
  15. col[rt<<1] = col[rt<<1|1] = col[rt];
  16. col[rt] = -1;
  17. }
  18. }
  19. void update(int L,int R,int c,int l,int r,int rt) {
  20. if (L <= l && r <= R) {
  21. col[rt] = c;
  22. return ;
  23. }
  24. PushDown(rt);
  25. int m = (l + r) >> 1;
  26. if (L <= m) update(L , R , c , lson);
  27. if (m < R) update(L , R , c , rson);
  28. }
  29. void query(int l,int r,int rt) {
  30. if (col[rt] != -1) {
  31. if (!hash[col[rt]]) cnt ++;
  32. hash[ col[rt] ] = true;
  33. return ;
  34. }
  35. if (l == r) return ;
  36. int m = (l + r) >> 1;
  37. query(lson);
  38. query(rson);
  39. }
  40. int Bin(int key,int n,int X[]) {
  41. int l = 0 , r = n - 1;
  42. while (l <= r) {
  43. int m = (l + r) >> 1;
  44. if (X[m] == key) return m;
  45. if (X[m] < key) l = m + 1;
  46. else r = m - 1;
  47. }
  48. return -1;
  49. }
  50. int main() {
  51. int T , n;
  52. scanf("%d",&T);
  53. while (T --) {
  54. scanf("%d",&n);
  55. int nn = 0;
  56. for (int i = 0 ; i < n ; i ++) {
  57. scanf("%d%d",&li[i] , &ri[i]);
  58. X[nn++] = li[i];
  59. X[nn++] = ri[i];
  60. }
  61. sort(X , X + nn);
  62. int m = 1;
  63. for (int i = 1 ; i < nn; i ++) {
  64. if (X[i] != X[i-1]) X[m ++] = X[i];
  65. }
  66. for (int i = m - 1 ; i > 0 ; i --) {
  67. if (X[i] != X[i-1] + 1) X[m ++] = X[i-1] + 1;
  68. }
  69. sort(X , X + m);
  70. memset(col , -1 , sizeof(col));
  71. for (int i = 0 ; i < n ; i ++) {
  72. int l = Bin(li[i] , m , X);
  73. int r = Bin(ri[i] , m , X);
  74. update(l , r , i , 0 , m , 1);
  75. }
  76. cnt = 0;
  77. memset(hash , false , sizeof(hash));
  78. query(0 , m , 1);
  79. printf("%d\n",cnt);
  80. }
  81. return 0;
  82. }
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
#define lson l , m , rt << 1
#define rson m + 1 , r , rt << 1 | 1

const int maxn = 11111;
bool hash[maxn];
int li[maxn] , ri[maxn];
int X[maxn*3];
int col[maxn<<4];
int cnt;

void PushDown(int rt) {
	if (col[rt] != -1) {
		col[rt<<1] = col[rt<<1|1] = col[rt];
		col[rt] = -1;
	}
}
void update(int L,int R,int c,int l,int r,int rt) {
	if (L <= l && r <= R) {
		col[rt] = c;
		return ;
	}
	PushDown(rt);
	int m = (l + r) >> 1;
	if (L <= m) update(L , R , c , lson);
	if (m < R) update(L , R , c , rson);
}
void query(int l,int r,int rt) {
	if (col[rt] != -1) {
		if (!hash[col[rt]]) cnt ++;
		hash[ col[rt] ] = true;
		return ;
	}
	if (l == r) return ;
	int m = (l + r) >> 1;
	query(lson);
	query(rson);
}
int Bin(int key,int n,int X[]) {
	int l = 0 , r = n - 1;
	while (l <= r) {
		int m = (l + r) >> 1;
		if (X[m] == key) return m;
		if (X[m] < key) l = m + 1;
		else r = m - 1;
	}
	return -1;
}
int main() {
	int T , n;
	scanf("%d",&T);
	while (T --) {
		scanf("%d",&n);
		int nn = 0;
		for (int i = 0 ; i < n ; i ++) {
			scanf("%d%d",&li[i] , &ri[i]);
			X[nn++] = li[i];
			X[nn++] = ri[i];
		}
		sort(X , X + nn);
		int m = 1;
		for (int i = 1 ; i < nn; i ++) {
			if (X[i] != X[i-1]) X[m ++] = X[i];
		}
		for (int i = m - 1 ; i > 0 ; i --) {
			if (X[i] != X[i-1] + 1) X[m ++] = X[i-1] + 1;
		}
		sort(X , X + m);
		memset(col , -1 , sizeof(col));
		for (int i = 0 ; i < n ; i ++) {
			int l = Bin(li[i] , m , X);
			int r = Bin(ri[i] , m , X);
			update(l , r , i , 0 , m , 1);
		}
		cnt = 0;
		memset(hash , false , sizeof(hash));
		query(0 , m , 1);
		printf("%d\n",cnt);
	}
	return 0;
}

poj3225 Help with Intervals
题意:区间操作,交,并,补等
思路:
我们一个一个操作来分析:(用0和1表示是否包含区间,-1表示该区间内既有包含又有不包含)
U:把区间[l,r]覆盖成1
I:把[-∞,l)(r,∞]覆盖成0
D:把区间[l,r]覆盖成0
C:把[-∞,l)(r,∞]覆盖成0 , 且[l,r]区间0/1互换
S:[l,r]区间0/1互换

成段覆盖的操作很简单,比较特殊的就是区间0/1互换这个操作,我们可以称之为异或操作
很明显我们可以知道这个性质:当一个区间被覆盖后,不管之前有没有异或标记都没有意义了
所以当一个节点得到覆盖标记时把异或标记清空
而当一个节点得到异或标记的时候,先判断覆盖标记,如果是0或1,直接改变一下覆盖标记,不然的话改变异或标记

开区间闭区间只要数字乘以2就可以处理(偶数表示端点,奇数表示两端点间的区间)
线段树功能:update:成段替换,区间异或 query:简单hash

[cpp] view plaincopyprint?

  1. #include <cstdio>
  2. #include <cstring>
  3. #include <cctype>
  4. #include <algorithm>
  5. using namespace std;
  6. #define lson l , m , rt << 1
  7. #define rson m + 1 , r , rt << 1 | 1
  8. const int maxn = 131072;
  9. bool hash[maxn+1];
  10. int cover[maxn<<2];
  11. int XOR[maxn<<2];
  12. void FXOR(int rt) {
  13. if (cover[rt] != -1) cover[rt] ^= 1;
  14. else XOR[rt] ^= 1;
  15. }
  16. void PushDown(int rt) {
  17. if (cover[rt] != -1) {
  18. cover[rt<<1] = cover[rt<<1|1] = cover[rt];
  19. XOR[rt<<1] = XOR[rt<<1|1] = 0;
  20. cover[rt] = -1;
  21. }
  22. if (XOR[rt]) {
  23. FXOR(rt<<1);
  24. FXOR(rt<<1|1);
  25. XOR[rt] = 0;
  26. }
  27. }
  28. void update(char op,int L,int R,int l,int r,int rt) {
  29. if (L <= l && r <= R) {
  30. if (op == ‘U‘) {
  31. cover[rt] = 1;
  32. XOR[rt] = 0;
  33. } else if (op == ‘D‘) {
  34. cover[rt] = 0;
  35. XOR[rt] = 0;
  36. } else if (op == ‘C‘ || op == ‘S‘) {
  37. FXOR(rt);
  38. }
  39. return ;
  40. }
  41. PushDown(rt);
  42. int m = (l + r) >> 1;
  43. if (L <= m) update(op , L , R , lson);
  44. else if (op == ‘I‘ || op == ‘C‘) {
  45. XOR[rt<<1] = cover[rt<<1] = 0;
  46. }
  47. if (m < R) update(op , L , R , rson);
  48. else if (op == ‘I‘ || op == ‘C‘) {
  49. XOR[rt<<1|1] = cover[rt<<1|1] = 0;
  50. }
  51. }
  52. void query(int l,int r,int rt) {
  53. if (cover[rt] == 1) {
  54. for (int it = l ; it <= r ; it ++) {
  55. hash[it] = true;
  56. }
  57. return ;
  58. } else if (cover[rt] == 0) return ;
  59. if (l == r) return ;
  60. PushDown(rt);
  61. int m = (l + r) >> 1;
  62. query(lson);
  63. query(rson);
  64. }
  65. int main() {
  66. cover[1] = XOR[1] = 0;
  67. char op , l , r;
  68. int a , b;
  69. while ( ~scanf("%c %c%d,%d%c\n",&op , &l , &a , &b , &r) ) {
  70. a <<= 1 , b <<= 1;
  71. if (l == ‘(‘) a ++;
  72. if (r == ‘)‘) b --;
  73. if (a > b) {
  74. if (op == ‘C‘ || op == ‘I‘) {
  75. cover[1] = XOR[1] = 0;
  76. }
  77. } else update(op , a , b , 0 , maxn , 1);
  78. }
  79. query(0 , maxn , 1);
  80. bool flag = false;
  81. int s = -1 , e;
  82. for (int i = 0 ; i <= maxn ; i ++) {
  83. if (hash[i]) {
  84. if (s == -1) s = i;
  85. e = i;
  86. } else {
  87. if (s != -1) {
  88. if (flag) printf(" ");
  89. flag = true;
  90. printf("%c%d,%d%c",s&1?‘(‘:‘[‘ , s>>1 , (e+1)>>1 , e&1?‘)‘:‘]‘);
  91. s = -1;
  92. }
  93. }
  94. }
  95. if (!flag) printf("empty set");
  96. puts("");
  97. return 0;
  98. }
#include <cstdio>
#include <cstring>
#include <cctype>
#include <algorithm>
using namespace std;
#define lson l , m , rt << 1
#define rson m + 1 , r , rt << 1 | 1

const int maxn = 131072;
bool hash[maxn+1];
int cover[maxn<<2];
int XOR[maxn<<2];
void FXOR(int rt) {
	if (cover[rt] != -1) cover[rt] ^= 1;
	else XOR[rt] ^= 1;
}
void PushDown(int rt) {
	if (cover[rt] != -1) {
		cover[rt<<1] = cover[rt<<1|1] = cover[rt];
		XOR[rt<<1] = XOR[rt<<1|1] = 0;
		cover[rt] = -1;
	}
	if (XOR[rt]) {
		FXOR(rt<<1);
		FXOR(rt<<1|1);
		XOR[rt] = 0;
	}
}
void update(char op,int L,int R,int l,int r,int rt) {
	if (L <= l && r <= R) {
		if (op == ‘U‘) {
			cover[rt] = 1;
			XOR[rt] = 0;
		} else if (op == ‘D‘) {
			cover[rt] = 0;
			XOR[rt] = 0;
		} else if (op == ‘C‘ || op == ‘S‘) {
			FXOR(rt);
		}
		return ;
	}
	PushDown(rt);
	int m = (l + r) >> 1;
	if (L <= m) update(op , L , R , lson);
	else if (op == ‘I‘ || op == ‘C‘) {
		XOR[rt<<1] = cover[rt<<1] = 0;
	}
	if (m < R) update(op , L , R , rson);
	else if (op == ‘I‘ || op == ‘C‘) {
		XOR[rt<<1|1] = cover[rt<<1|1] = 0;
	}
}
void query(int l,int r,int rt) {
	if (cover[rt] == 1) {
		for (int it = l ; it <= r ; it ++) {
			hash[it] = true;
		}
		return ;
	} else if (cover[rt] == 0) return ;
	if (l == r) return ;
	PushDown(rt);
	int m = (l + r) >> 1;
	query(lson);
	query(rson);
}
int main() {
	cover[1] = XOR[1] = 0;
	char op , l , r;
	int a , b;
	while ( ~scanf("%c %c%d,%d%c\n",&op , &l , &a , &b , &r) ) {
		a <<= 1 , b <<= 1;
		if (l == ‘(‘) a ++;
		if (r == ‘)‘) b --;
		if (a > b) {
			if (op == ‘C‘ || op == ‘I‘) {
				cover[1] = XOR[1] = 0;
			}
		} else update(op , a , b , 0 , maxn , 1);
	}
	query(0 , maxn , 1);
	bool flag = false;
	int s = -1 , e;
	for (int i = 0 ; i <= maxn ; i ++) {
		if (hash[i]) {
			if (s == -1) s = i;
			e = i;
		} else {
			if (s != -1) {
				if (flag) printf(" ");
				flag = true;
				printf("%c%d,%d%c",s&1?‘(‘:‘[‘ , s>>1 , (e+1)>>1 , e&1?‘)‘:‘]‘);
				s = -1;
			}
		}
	}
	if (!flag) printf("empty set");
	puts("");
	return 0;
}

练习
poj1436 Horizontally Visible Segments
poj2991 Crane
Another LCIS
Bracket Sequence

区间合并

这类题目会询问区间中满足条件的连续最长区间,所以PushUp的时候需要对左右儿子的区间进行合并

poj3667 Hotel
题意:1 a:询问是不是有连续长度为a的空房间,有的话住进最左边
2 a b:将[a,a+b-1]的房间清空
思路:记录区间中最长的空房间
线段树操作:update:区间替换 query:询问满足条件的最左断点

[cpp] view plaincopyprint?

  1. #include <cstdio>
  2. #include <cstring>
  3. #include <cctype>
  4. #include <algorithm>
  5. using namespace std;
  6. #define lson l , m , rt << 1
  7. #define rson m + 1 , r , rt << 1 | 1
  8. const int maxn = 55555;
  9. int lsum[maxn<<2] , rsum[maxn<<2] , msum[maxn<<2];
  10. int cover[maxn<<2];
  11. void PushDown(int rt,int m) {
  12. if (cover[rt] != -1) {
  13. cover[rt<<1] = cover[rt<<1|1] = cover[rt];
  14. msum[rt<<1] = lsum[rt<<1] = rsum[rt<<1] = cover[rt] ? 0 : m - (m >> 1);
  15. msum[rt<<1|1] = lsum[rt<<1|1] = rsum[rt<<1|1] = cover[rt] ? 0 : (m >> 1);
  16. cover[rt] = -1;
  17. }
  18. }
  19. void PushUp(int rt,int m) {
  20. lsum[rt] = lsum[rt<<1];
  21. rsum[rt] = rsum[rt<<1|1];
  22. if (lsum[rt] == m - (m >> 1)) lsum[rt] += lsum[rt<<1|1];
  23. if (rsum[rt] == (m >> 1)) rsum[rt] += rsum[rt<<1];
  24. msum[rt] = max(lsum[rt<<1|1] + rsum[rt<<1] , max(msum[rt<<1] , msum[rt<<1|1]));
  25. }
  26. void build(int l,int r,int rt) {
  27. msum[rt] = lsum[rt] = rsum[rt] = r - l + 1;
  28. cover[rt] = -1;
  29. if (l == r) return ;
  30. int m = (l + r) >> 1;
  31. build(lson);
  32. build(rson);
  33. }
  34. void update(int L,int R,int c,int l,int r,int rt) {
  35. if (L <= l && r <= R) {
  36. msum[rt] = lsum[rt] = rsum[rt] = c ? 0 : r - l + 1;
  37. cover[rt] = c;
  38. return ;
  39. }
  40. PushDown(rt , r - l + 1);
  41. int m = (l + r) >> 1;
  42. if (L <= m) update(L , R , c , lson);
  43. if (m < R) update(L , R , c , rson);
  44. PushUp(rt , r - l + 1);
  45. }
  46. int query(int w,int l,int r,int rt) {
  47. if (l == r) return l;
  48. PushDown(rt , r - l + 1);
  49. int m = (l + r) >> 1;
  50. if (msum[rt<<1] >= w) return query(w , lson);
  51. else if (rsum[rt<<1] + lsum[rt<<1|1] >= w) return m - rsum[rt<<1] + 1;
  52. return query(w , rson);
  53. }
  54. int main() {
  55. int n , m;
  56. scanf("%d%d",&n,&m);
  57. build(1 , n , 1);
  58. while (m --) {
  59. int op , a , b;
  60. scanf("%d",&op);
  61. if (op == 1) {
  62. scanf("%d",&a);
  63. if (msum[1] < a) puts("0");
  64. else {
  65. int p = query(a , 1 , n , 1);
  66. printf("%d\n",p);
  67. update(p , p + a - 1 , 1 , 1 , n , 1);
  68. }
  69. } else {
  70. scanf("%d%d",&a,&b);
  71. update(a , a + b - 1 , 0 , 1 , n , 1);
  72. }
  73. }
  74. return 0;
  75. }
#include <cstdio>
#include <cstring>
#include <cctype>
#include <algorithm>
using namespace std;
#define lson l , m , rt << 1
#define rson m + 1 , r , rt << 1 | 1

const int maxn = 55555;
int lsum[maxn<<2] , rsum[maxn<<2] , msum[maxn<<2];
int cover[maxn<<2];

void PushDown(int rt,int m) {
	if (cover[rt] != -1) {
		cover[rt<<1] = cover[rt<<1|1] = cover[rt];
		msum[rt<<1] = lsum[rt<<1] = rsum[rt<<1] = cover[rt] ? 0 : m - (m >> 1);
		msum[rt<<1|1] = lsum[rt<<1|1] = rsum[rt<<1|1] = cover[rt] ? 0 : (m >> 1);
		cover[rt] = -1;
	}
}
void PushUp(int rt,int m) {
	lsum[rt] = lsum[rt<<1];
	rsum[rt] = rsum[rt<<1|1];
	if (lsum[rt] == m - (m >> 1)) lsum[rt] += lsum[rt<<1|1];
	if (rsum[rt] == (m >> 1)) rsum[rt] += rsum[rt<<1];
	msum[rt] = max(lsum[rt<<1|1] + rsum[rt<<1] , max(msum[rt<<1] , msum[rt<<1|1]));
}
void build(int l,int r,int rt) {
	msum[rt] = lsum[rt] = rsum[rt] = r - l + 1;
	cover[rt] = -1;
	if (l == r) return ;
	int m = (l + r) >> 1;
	build(lson);
	build(rson);
}
void update(int L,int R,int c,int l,int r,int rt) {
	if (L <= l && r <= R) {
		msum[rt] = lsum[rt] = rsum[rt] = c ? 0 : r - l + 1;
		cover[rt] = c;
		return ;
	}
	PushDown(rt , r - l + 1);
	int m = (l + r) >> 1;
	if (L <= m) update(L , R , c , lson);
	if (m < R) update(L , R , c , rson);
	PushUp(rt , r - l + 1);
}
int query(int w,int l,int r,int rt) {
	if (l == r) return l;
	PushDown(rt , r - l + 1);
	int m = (l + r) >> 1;
	if (msum[rt<<1] >= w) return query(w , lson);
	else if (rsum[rt<<1] + lsum[rt<<1|1] >= w) return m - rsum[rt<<1] + 1;
	return query(w , rson);
}
int main() {
	int n , m;
	scanf("%d%d",&n,&m);
	build(1 , n , 1);
	while (m --) {
		int op , a , b;
		scanf("%d",&op);
		if (op == 1) {
			scanf("%d",&a);
			if (msum[1] < a) puts("0");
			else {
				int p = query(a , 1 , n , 1);
				printf("%d\n",p);
				update(p , p + a - 1 , 1 , 1 , n , 1);
			}
		} else {
			scanf("%d%d",&a,&b);
			update(a , a + b - 1 , 0 , 1 , n , 1);
		}
	}
	return 0;
}

练习
hdu3308 LCIS
hdu3397 Sequence operation
hdu2871 Memory Control
hdu1540 Tunnel Warfare
CF46-D Parking Lot

扫描线

这类题目需要将一些操作排序,然后从左到右用一根扫描线(当然是在我们脑子里)扫过去
最典型的就是矩形面积并,周长并等题

hdu1542 Atlantis
题意:矩形面积并
思路:浮点数先要离散化;然后把矩形分成两条边,上边和下边,对横轴建树,然后从下到上扫描上去,用cnt表示该区间下边比上边多几个,sum代表该区间内被覆盖的线段的长度总和
这里线段树的一个结点并非是线段的一个端点,而是该端点和下一个端点间的线段,所以题目中r+1,r-1的地方可以自己好好的琢磨一下

线段树操作:update:区间增减 query:直接取根节点的值

[cpp] view plaincopyprint?

  1. #include <cstdio>
  2. #include <cstring>
  3. #include <cctype>
  4. #include <algorithm>
  5. using namespace std;
  6. #define lson l , m , rt << 1
  7. #define rson m + 1 , r , rt << 1 | 1
  8. const int maxn = 2222;
  9. int cnt[maxn << 2];
  10. double sum[maxn << 2];
  11. double X[maxn];
  12. struct Seg {
  13. double h , l , r;
  14. int s;
  15. Seg(){}
  16. Seg(double a,double b,double c,int d) : l(a) , r(b) , h(c) , s(d) {}
  17. bool operator < (const Seg &cmp) const {
  18. return h < cmp.h;
  19. }
  20. }ss[maxn];
  21. void PushUp(int rt,int l,int r) {
  22. if (cnt[rt]) sum[rt] = X[r+1] - X[l];
  23. else if (l == r) sum[rt] = 0;
  24. else sum[rt] = sum[rt<<1] + sum[rt<<1|1];
  25. }
  26. void update(int L,int R,int c,int l,int r,int rt) {
  27. if (L <= l && r <= R) {
  28. cnt[rt] += c;
  29. PushUp(rt , l , r);
  30. return ;
  31. }
  32. int m = (l + r) >> 1;
  33. if (L <= m) update(L , R , c , lson);
  34. if (m < R) update(L , R , c , rson);
  35. PushUp(rt , l , r);
  36. }
  37. int Bin(double key,int n,double X[]) {
  38. int l = 0 , r = n - 1;
  39. while (l <= r) {
  40. int m = (l + r) >> 1;
  41. if (X[m] == key) return m;
  42. if (X[m] < key) l = m + 1;
  43. else r = m - 1;
  44. }
  45. return -1;
  46. }
  47. int main() {
  48. int n , cas = 1;
  49. while (~scanf("%d",&n) && n) {
  50. int m = 0;
  51. while (n --) {
  52. double a , b , c , d;
  53. scanf("%lf%lf%lf%lf",&a,&b,&c,&d);
  54. X[m] = a;
  55. ss[m++] = Seg(a , c , b , 1);
  56. X[m] = c;
  57. ss[m++] = Seg(a , c , d , -1);
  58. }
  59. sort(X , X + m);
  60. sort(ss , ss + m);
  61. int k = 1;
  62. for (int i = 1 ; i < m ; i ++) {
  63. if (X[i] != X[i-1]) X[k++] = X[i];
  64. }
  65. memset(cnt , 0 , sizeof(cnt));
  66. memset(sum , 0 , sizeof(sum));
  67. double ret = 0;
  68. for (int i = 0 ; i < m - 1 ; i ++) {
  69. int l = Bin(ss[i].l , k , X);
  70. int r = Bin(ss[i].r , k , X) - 1;
  71. if (l <= r) update(l , r , ss[i].s , 0 , k - 1, 1);
  72. ret += sum[1] * (ss[i+1].h - ss[i].h);
  73. }
  74. printf("Test case #%d\nTotal explored area: %.2lf\n\n",cas++ , ret);
  75. }
  76. return 0;
  77. }
#include <cstdio>
#include <cstring>
#include <cctype>
#include <algorithm>
using namespace std;
#define lson l , m , rt << 1
#define rson m + 1 , r , rt << 1 | 1

const int maxn = 2222;
int cnt[maxn << 2];
double sum[maxn << 2];
double X[maxn];
struct Seg {
	double h , l , r;
	int s;
	Seg(){}
	Seg(double a,double b,double c,int d) : l(a) , r(b) , h(c) , s(d) {}
	bool operator < (const Seg &cmp) const {
		return h < cmp.h;
	}
}ss[maxn];
void PushUp(int rt,int l,int r) {
	if (cnt[rt]) sum[rt] = X[r+1] - X[l];
	else if (l == r) sum[rt] = 0;
	else sum[rt] = sum[rt<<1] + sum[rt<<1|1];
}
void update(int L,int R,int c,int l,int r,int rt) {
	if (L <= l && r <= R) {
		cnt[rt] += c;
		PushUp(rt , l , r);
		return ;
	}
	int m = (l + r) >> 1;
	if (L <= m) update(L , R , c , lson);
	if (m < R) update(L , R , c , rson);
	PushUp(rt , l , r);
}
int Bin(double key,int n,double X[]) {
	int l = 0 , r = n - 1;
	while (l <= r) {
		int m = (l + r) >> 1;
		if (X[m] == key) return m;
		if (X[m] < key) l = m + 1;
		else r = m - 1;
	}
	return -1;
}
int main() {
	int n , cas = 1;
	while (~scanf("%d",&n) && n) {
		int m = 0;
		while (n --) {
			double a , b , c , d;
			scanf("%lf%lf%lf%lf",&a,&b,&c,&d);
			X[m] = a;
			ss[m++] = Seg(a , c , b , 1);
			X[m] = c;
			ss[m++] = Seg(a , c , d , -1);
		}
		sort(X , X + m);
		sort(ss , ss + m);
		int k = 1;
		for (int i = 1 ; i < m ; i ++) {
			if (X[i] != X[i-1]) X[k++] = X[i];
		}
		memset(cnt , 0 , sizeof(cnt));
		memset(sum , 0 , sizeof(sum));
		double ret = 0;
		for (int i = 0 ; i < m - 1 ; i ++) {
			int l = Bin(ss[i].l , k , X);
			int r = Bin(ss[i].r , k , X) - 1;
			if (l <= r) update(l , r , ss[i].s , 0 , k - 1, 1);
			ret += sum[1] * (ss[i+1].h - ss[i].h);
		}
		printf("Test case #%d\nTotal explored area: %.2lf\n\n",cas++ , ret);
	}
	return 0;
}

 

hdu1828 Picture
题意:矩形周长并
思路:与面积不同的地方是还要记录竖的边有几个(numseg记录),并且当边界重合的时候需要合并(用lbd和rbd表示边界来辅助)
线段树操作:update:区间增减 query:直接取根节点的值

[cpp] view plaincopyprint?

  1. #include <cstdio>
  2. #include <cstring>
  3. #include <cctype>
  4. #include <algorithm>
  5. using namespace std;
  6. #define lson l , m , rt << 1
  7. #define rson m + 1 , r , rt << 1 | 1
  8. const int maxn = 22222;
  9. struct Seg{
  10. int l , r , h , s;
  11. Seg() {}
  12. Seg(int a,int b,int c,int d):l(a) , r(b) , h(c) , s(d) {}
  13. bool operator < (const Seg &cmp) const {
  14. if (h == cmp.h) return s > cmp.s;
  15. return h < cmp.h;
  16. }
  17. }ss[maxn];
  18. bool lbd[maxn<<2] , rbd[maxn<<2];
  19. int numseg[maxn<<2];
  20. int cnt[maxn<<2];
  21. int len[maxn<<2];
  22. void PushUP(int rt,int l,int r) {
  23. if (cnt[rt]) {
  24. lbd[rt] = rbd[rt] = 1;
  25. len[rt] = r - l + 1;
  26. numseg[rt] = 2;
  27. } else if (l == r) {
  28. len[rt] = numseg[rt] = lbd[rt] = rbd[rt] = 0;
  29. } else {
  30. lbd[rt] = lbd[rt<<1];
  31. rbd[rt] = rbd[rt<<1|1];
  32. len[rt] = len[rt<<1] + len[rt<<1|1];
  33. numseg[rt] = numseg[rt<<1] + numseg[rt<<1|1];
  34. if (lbd[rt<<1|1] && rbd[rt<<1]) numseg[rt] -= 2;//两条线重合
  35. }
  36. }
  37. void update(int L,int R,int c,int l,int r,int rt) {
  38. if (L <= l && r <= R) {
  39. cnt[rt] += c;
  40. PushUP(rt , l , r);
  41. return ;
  42. }
  43. int m = (l + r) >> 1;
  44. if (L <= m) update(L , R , c , lson);
  45. if (m < R) update(L , R , c , rson);
  46. PushUP(rt , l , r);
  47. }
  48. int main() {
  49. int n;
  50. while (~scanf("%d",&n)) {
  51. int m = 0;
  52. int lbd = 10000, rbd = -10000;
  53. for (int i = 0 ; i < n ; i ++) {
  54. int a , b , c , d;
  55. scanf("%d%d%d%d",&a,&b,&c,&d);
  56. lbd = min(lbd , a);
  57. rbd = max(rbd , c);
  58. ss[m++] = Seg(a , c , b , 1);
  59. ss[m++] = Seg(a , c , d , -1);
  60. }
  61. sort(ss , ss + m);
  62. int ret = 0 , last = 0;
  63. for (int i = 0 ; i < m ; i ++) {
  64. if (ss[i].l < ss[i].r) update(ss[i].l , ss[i].r - 1 , ss[i].s , lbd , rbd - 1 , 1);
  65. ret += numseg[1] * (ss[i+1].h - ss[i].h);
  66. ret += abs(len[1] - last);
  67. last = len[1];
  68. }
  69. printf("%d\n",ret);
  70. }
  71. return 0;
  72. }
#include <cstdio>
#include <cstring>
#include <cctype>
#include <algorithm>
using namespace std;
#define lson l , m , rt << 1
#define rson m + 1 , r , rt << 1 | 1

const int maxn = 22222;
struct Seg{
	int l , r , h , s;
	Seg() {}
	Seg(int a,int b,int c,int d):l(a) , r(b) , h(c) , s(d) {}
	bool operator < (const Seg &cmp) const {
		if (h == cmp.h) return s > cmp.s;
		return h < cmp.h;
	}
}ss[maxn];
bool lbd[maxn<<2] , rbd[maxn<<2];
int numseg[maxn<<2];
int cnt[maxn<<2];
int len[maxn<<2];
void PushUP(int rt,int l,int r) {
	if (cnt[rt]) {
		lbd[rt] = rbd[rt] = 1;
		len[rt] = r - l + 1;
		numseg[rt] = 2;
	} else if (l == r) {
		len[rt] = numseg[rt] = lbd[rt] = rbd[rt] = 0;
	} else {
		lbd[rt] = lbd[rt<<1];
		rbd[rt] = rbd[rt<<1|1];
		len[rt] = len[rt<<1] + len[rt<<1|1];
		numseg[rt] = numseg[rt<<1] + numseg[rt<<1|1];
		if (lbd[rt<<1|1] && rbd[rt<<1]) numseg[rt] -= 2;//两条线重合
	}
}
void update(int L,int R,int c,int l,int r,int rt) {
	if (L <= l && r <= R) {
		cnt[rt] += c;
		PushUP(rt , l , r);
		return ;
	}
	int m = (l + r) >> 1;
	if (L <= m) update(L , R , c , lson);
	if (m < R) update(L , R , c , rson);
	PushUP(rt , l , r);
}
int main() {
	int n;
	while (~scanf("%d",&n)) {
		int m = 0;
		int lbd = 10000, rbd = -10000;
		for (int i = 0 ; i < n ; i ++) {
			int a , b , c , d;
			scanf("%d%d%d%d",&a,&b,&c,&d);
			lbd = min(lbd , a);
			rbd = max(rbd , c);
			ss[m++] = Seg(a , c , b , 1);
			ss[m++] = Seg(a , c , d , -1);
		}
		sort(ss , ss + m);
		int ret = 0 , last = 0;
		for (int i = 0 ; i < m ; i ++) {
			if (ss[i].l < ss[i].r) update(ss[i].l , ss[i].r - 1 , ss[i].s , lbd , rbd - 1 , 1);
			ret += numseg[1] * (ss[i+1].h - ss[i].h);
			ret += abs(len[1] - last);
			last = len[1];
		}
		printf("%d\n",ret);
	}
	return 0;
}

练习
hdu3265 Posters
hdu3642 Get The Treasury
poj2482 Stars in Your Window
poj2464 Brownie Points II
hdu3255 Farming
ural1707 Hypnotoad’s Secret
uva11983 Weird Advertisement

 

多颗线段树问题

此类题目主用特点是区间不连续,有一定规律间隔,用多棵树表示不同的偏移区间

hdu 4288 coder

题意:
维护一个有序数列{An},有三种操作:
1、添加一个元素。
2、删除一个元素。
3、求数列中下标%5 = 3的值的和。

由于有删除和添加操作,所以离线离散操作,节点中cnt存储区间中有几个数,sum存储偏移和

[cpp] view plaincopyprint?

  1. #include<iostream>
  2. #include<cstdio>
  3. #include<cstring>
  4. #include<algorithm>
  5. using namespace std;
  6. const int maxn=100002;
  7. #define lson l , m , rt << 1
  8. #define rson m + 1 , r , rt << 1 | 1
  9. __int64 sum[maxn<<2][6];
  10. int cnt[maxn << 2];
  11. char op[maxn][20];
  12. int a[maxn];
  13. int X[maxn];
  14. void PushUp(int rt)
  15. {
  16. cnt[rt] = cnt[rt<<1] + cnt[rt<<1|1];
  17. int offset = cnt[rt<<1];
  18. for(int i = 0; i < 5; ++i)
  19. {
  20. sum[rt][i] = sum[rt<<1][i];
  21. }
  22. for(int i = 0; i < 5; ++i)
  23. {
  24. sum[rt][(i + offset) % 5] += sum[rt<<1|1][i];
  25. }
  26. }
  27. void Build(int l, int r, int rt)
  28. {   /*此题Build完全可以用一个memset代替*/
  29. cnt[rt] = 0;
  30. for(int i = 0; i < 5; ++i)   sum[rt][i] = 0;
  31. if( l == r ) return;
  32. int m = ( l + r )>>1;
  33. Build(lson);
  34. Build(rson);
  35. }
  36. void Updata(int p, int op, int l, int r, int rt)
  37. {
  38. if( l == r )
  39. {
  40. cnt[rt] = op;
  41. sum[rt][1] = op * X[l-1];
  42. return ;
  43. }
  44. int m = ( l + r ) >> 1;
  45. if(p <= m)
  46. Updata(p, op, lson);
  47. else
  48. Updata(p, op, rson);
  49. PushUp(rt);
  50. }
  51. int main()
  52. {
  53. int n;
  54. while(scanf("%d", &n) != EOF)
  55. {
  56. int nn = 0;
  57. for(int i = 0; i < n; ++i)
  58. {
  59. scanf("%s", &op[i]);
  60. if(op[i][0] != ‘s‘)
  61. {
  62. scanf("%d", &a[i]);
  63. if(op[i][0] == ‘a‘)
  64. {
  65. X[nn++] = a[i];
  66. }
  67. }
  68. }
  69. sort(X,X+nn);/*unique前必须sort*/
  70. nn = unique(X, X + nn) - X; /*去重并得到总数*/
  71. Build(1, nn, 1);
  72. for(int i = 0; i < n; ++i)
  73. {
  74. int pos = upper_bound(X, X+nn, a[i]) - X; /* hash */
  75. if(op[i][0] == ‘a‘)
  76. {
  77. Updata(pos, 1, 1, nn, 1);
  78. }
  79. else if(op[i][0] == ‘d‘)
  80. {
  81. Updata(pos, 0, 1, nn, 1);
  82. }
  83. else printf("%I64d\n",sum[1][3]);
  84. }
  85. }
  86. return 0;
  87. }
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn=100002;

#define lson l , m , rt << 1
#define rson m + 1 , r , rt << 1 | 1 

__int64 sum[maxn<<2][6];
int cnt[maxn << 2];

char op[maxn][20];
int a[maxn];

int X[maxn];

void PushUp(int rt)
{
    cnt[rt] = cnt[rt<<1] + cnt[rt<<1|1];

    int offset = cnt[rt<<1];
    for(int i = 0; i < 5; ++i)
    {
        sum[rt][i] = sum[rt<<1][i];
    }
    for(int i = 0; i < 5; ++i)
    {
        sum[rt][(i + offset) % 5] += sum[rt<<1|1][i];
    }
}

void Build(int l, int r, int rt)
{  	/*此题Build完全可以用一个memset代替*/
	cnt[rt] = 0;
	for(int i = 0; i < 5; ++i)	sum[rt][i] = 0;
    if( l == r ) return;
	int m = ( l + r )>>1;
    Build(lson);
    Build(rson);
} 

void Updata(int p, int op, int l, int r, int rt)
{
    if( l == r )
    {
        cnt[rt] = op;
		sum[rt][1] = op * X[l-1];
        return ;
    }
    int m = ( l + r ) >> 1;
    if(p <= m)
        Updata(p, op, lson);
    else
        Updata(p, op, rson);  

    PushUp(rt);
} 

int main()
{
	int n;
    while(scanf("%d", &n) != EOF)
    {
        int nn = 0;
        for(int i = 0; i < n; ++i)
        {
            scanf("%s", &op[i]);

            if(op[i][0] != ‘s‘)
            {
                scanf("%d", &a[i]);
                if(op[i][0] == ‘a‘)
                {
                    X[nn++] = a[i];
                }
            }
        }

		sort(X,X+nn);/*unique前必须sort*/
        nn = unique(X, X + nn) - X; /*去重并得到总数*/

		Build(1, nn, 1);

		for(int i = 0; i < n; ++i)
        {
            int pos = upper_bound(X, X+nn, a[i]) - X; /* hash */
            if(op[i][0] == ‘a‘)
            {
                Updata(pos, 1, 1, nn, 1);
            }
            else if(op[i][0] == ‘d‘)
            {
                Updata(pos, 0, 1, nn, 1);
            }
            else printf("%I64d\n",sum[1][3]);
        }
    }
    return 0;
}

2:hdu 4267 A simple problem with integers

题目:给出n个数,每次将一段区间内满足(i-l)%k==0  (r>=i>=l) 的数ai增加c, 最后单点查询。

这种题目更新的区间是零散的,如果可以通过某种方式让离散的都变得连续,那么问题就可以用线段树完美解决。解决方式一般也是固定的,那就是利用题意维护多颗线段树。此题虚维护55颗,更新最终确定在一颗上,查询则将查询点被包含的树全部叠加。

[cpp] view plaincopyprint?

  1. #include<iostream>
  2. #include<cstdio>
  3. #include<cstring>
  4. #include<cmath>
  5. #include<algorithm>
  6. #include<set>
  7. #include<vector>
  8. #include<string>
  9. #include<map>
  10. #define eps 1e-7
  11. #define LL long long
  12. #define N 500005
  13. #define zero(a) fabs(a)<eps
  14. #define lson step<<1
  15. #define rson step<<1|1
  16. #define MOD 1234567891
  17. #define pb(a) push_back(a)
  18. using namespace std;
  19. struct Node{
  20. int left,right,add[55],sum;
  21. int mid(){return (left+right)/2;}
  22. }L[4*N];
  23. int a[N],n,b[11][11];
  24. void Bulid(int step ,int l,int r){
  25. L[step].left=l;
  26. L[step].right=r;
  27. L[step].sum=0;
  28. memset(L[step].add,0,sizeof(L[step].add));
  29. if(l==r) return ;
  30. Bulid(lson,l,L[step].mid());
  31. Bulid(rson,L[step].mid()+1,r);
  32. }
  33. void push_down(int step){
  34. if(L[step].sum){
  35. L[lson].sum+=L[step].sum;
  36. L[rson].sum+=L[step].sum;
  37. L[step].sum=0;
  38. for(int i=0;i<55;i++){
  39. L[lson].add[i]+=L[step].add[i];
  40. L[rson].add[i]+=L[step].add[i];
  41. L[step].add[i]=0;
  42. }
  43. }
  44. }
  45. void update(int step,int l,int r,int num,int i,int j){
  46. if(L[step].left==l&&L[step].right==r){
  47. L[step].sum+=num;
  48. L[step].add[b[i][j]]+=num;
  49. return;
  50. }
  51. push_down(step);
  52. if(r<=L[step].mid()) update(lson,l,r,num,i,j);
  53. else if(l>L[step].mid()) update(rson,l,r,num,i,j);
  54. else {
  55. update(lson,l,L[step].mid(),num,i,j);
  56. update(rson,L[step].mid()+1,r,num,i,j);
  57. }
  58. }
  59. int query(int step,int pos){
  60. if(L[step].left==L[step].right){
  61. int tmp=0;
  62. for(int i=1;i<=10;i++)  tmp+=L[step].add[b[i][pos%i]];
  63. return a[L[step].left]+tmp;
  64. }
  65. push_down(step);
  66. if(pos<=L[step].mid()) return query(lson,pos);
  67. else return query(rson,pos);
  68. }
  69. int main(){
  70. int cnt=0;
  71. for(int i=1;i<=10;i++) for(int j=0;j<i;j++) b[i][j]=cnt++;
  72. while(scanf("%d",&n)!=EOF){
  73. for(int i=1;i<=n;i++) scanf("%d",&a[i]);
  74. Bulid(1,1,n);
  75. int q,d;
  76. scanf("%d",&q);
  77. while(q--){
  78. int k,l,r,m;
  79. scanf("%d",&k);
  80. if(k==2){
  81. scanf("%d",&m);
  82. printf("%d\n",query(1,m));
  83. }
  84. else{
  85. scanf("%d%d%d%d",&l,&r,&d,&m);
  86. update(1,l,r,m,d,l%d);
  87. }
  88. }
  89. }
  90. return 0;
  91. }
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<set>
#include<vector>
#include<string>
#include<map>
#define eps 1e-7
#define LL long long
#define N 500005
#define zero(a) fabs(a)<eps
#define lson step<<1
#define rson step<<1|1
#define MOD 1234567891
#define pb(a) push_back(a)
using namespace std;
struct Node{
    int left,right,add[55],sum;
    int mid(){return (left+right)/2;}
}L[4*N];
int a[N],n,b[11][11];
void Bulid(int step ,int l,int r){
    L[step].left=l;
    L[step].right=r;
    L[step].sum=0;
    memset(L[step].add,0,sizeof(L[step].add));
    if(l==r) return ;
    Bulid(lson,l,L[step].mid());
    Bulid(rson,L[step].mid()+1,r);
}
void push_down(int step){
    if(L[step].sum){
        L[lson].sum+=L[step].sum;
        L[rson].sum+=L[step].sum;
        L[step].sum=0;
        for(int i=0;i<55;i++){
                L[lson].add[i]+=L[step].add[i];
                L[rson].add[i]+=L[step].add[i];
                L[step].add[i]=0;
        }
    }
}
void update(int step,int l,int r,int num,int i,int j){
    if(L[step].left==l&&L[step].right==r){
        L[step].sum+=num;
        L[step].add[b[i][j]]+=num;
        return;
    }
    push_down(step);
    if(r<=L[step].mid()) update(lson,l,r,num,i,j);
    else if(l>L[step].mid()) update(rson,l,r,num,i,j);
    else {
        update(lson,l,L[step].mid(),num,i,j);
        update(rson,L[step].mid()+1,r,num,i,j);
    }
}
int query(int step,int pos){
    if(L[step].left==L[step].right){
        int tmp=0;
        for(int i=1;i<=10;i++)  tmp+=L[step].add[b[i][pos%i]];
        return a[L[step].left]+tmp;
    }
    push_down(step);
    if(pos<=L[step].mid()) return query(lson,pos);
    else return query(rson,pos);
}
int main(){
    int cnt=0;
    for(int i=1;i<=10;i++) for(int j=0;j<i;j++) b[i][j]=cnt++;
    while(scanf("%d",&n)!=EOF){
        for(int i=1;i<=n;i++) scanf("%d",&a[i]);
        Bulid(1,1,n);
        int q,d;
        scanf("%d",&q);
        while(q--){
            int k,l,r,m;
            scanf("%d",&k);
            if(k==2){
                scanf("%d",&m);
                printf("%d\n",query(1,m));
            }
            else{
                scanf("%d%d%d%d",&l,&r,&d,&m);
                update(1,l,r,m,d,l%d);
            }
        }
    }
    return 0;
}

线段树与其他结合练习(欢迎大家补充):

时间: 2024-08-01 21:07:52

线段树(转)的相关文章

[poj2104]可持久化线段树入门题(主席树)

解题关键:离线求区间第k小,主席树的经典裸题: 对主席树的理解:主席树维护的是一段序列中某个数字出现的次数,所以需要预先离散化,最好使用vector的erase和unique函数,很方便:如果求整段序列的第k小,我们会想到离散化二分和线段树的做法, 而主席树只是保存了序列的前缀和,排序之后,对序列的前缀分别做线段树,具有差分的性质,因此可以求任意区间的第k小,如果主席树维护索引,只需要求出某个数字在主席树中的位置,即为sort之后v中的索引:若要求第k大,建树时反向排序即可 1 #include

【BZOJ4942】[Noi2017]整数 线段树+DFS(卡过)

[BZOJ4942][Noi2017]整数 题目描述去uoj 题解:如果只有加法,那么直接暴力即可...(因为1的数量最多nlogn个) 先考虑加法,比较显然的做法就是将A二进制分解成log位,然后依次更新这log位,如果最高位依然有进位,那么找到最高位后面的第一个0,将中间的所有1变成0,那个0变成1.这个显然要用到线段树,但是复杂度是nlog2n的,肯定过不去. 于是我在考场上yy了一下,这log位是连续的,我们每次都要花费log的时间去修改一个岂不是很浪费?我们可以先在线段树上找到这段区间

bzoj1798: [Ahoi2009]Seq 维护序列seq 线段树

题目传送门 这道题就是线段树 先传乘法标记再传加法 #include<cstdio> #include<cstring> #include<algorithm> #define LL long long using namespace std; const int M=400010; LL read(){ LL ans=0,f=1,c=getchar(); while(c<'0'||c>'9'){if(c=='-') f=-1; c=getchar();}

Vijos P1066 弱弱的战壕【多解,线段树,暴力,树状数组】

弱弱的战壕 描述 永恒和mx正在玩一个即时战略游戏,名字嘛~~~~~~恕本人记性不好,忘了-_-b. mx在他的基地附近建立了n个战壕,每个战壕都是一个独立的作战单位,射程可以达到无限(“mx不赢定了?!?”永恒[email protected][email protected]). 但是,战壕有一个弱点,就是只能攻击它的左下方,说白了就是横纵坐标都不大于它的点(mx:“我的战壕为什么这么菜”ToT).这样,永恒就可以从别的地方进攻摧毁战壕,从而消灭mx的部队. 战壕都有一个保护范围,同它的攻击

luogu 1712 区间(线段树+尺取法)

题意:给出n个区间,求选择一些区间,使得一个点被覆盖的次数超过m次,最小的花费.花费指的是选择的区间中最大长度减去最小长度. 坐标值这么大,n比较小,显然需要离散化,需要一个技巧,把区间转化为半开半闭区间,然后线段树的每一个节点表示一个半开半闭区间. 接着我们注意到需要求最小的花费,且这个花费只与选择的区间集合中的最大长度和最小长度有关. 这意味着如果最大长度和最小长度一定,我们显然是需要把中间长度的区间尽量的选择进去使答案不会变的更劣. 不妨把区间按长度排序,枚举每个最小长度区间,然后最大区间

【BZOJ】1382: [Baltic2001]Mars Maps (线段树+扫描线)

1382: [Baltic2001]Mars Maps Time Limit: 5 Sec  Memory Limit: 64 MB Description 给出N个矩形,N<=10000.其坐标不超过10^9.求其面积并 Input 先给出一个数字N,代表有N个矩形. 接下来N行,每行四个数,代表矩形的坐标. Output 输出面积并 Sample Input 2 10 10 20 20 15 15 25 30 Sample Output 225 本以为是傻逼题,没想到不容易啊- 线段树+扫描

BZOJ 1012: [JSOI2008]最大数maxnumber(线段树)

012: [JSOI2008]最大数maxnumber Time Limit: 3 Sec  Memory Limit: 162 MB Description 现在请求你维护一个数列,要求提供以下两种操作:1. 查询操作.语法:Q L 功能:查询当前数列中末尾L个数中的最大的数,并输出这个数的值.限制:L不超过当前数列的长度.2. 插入操作.语法:A n 功能:将n加上t,其中t是最近一次查询操作的答案(如果还未执行过查询操作,则t=0),并将所得结果对一个固定的常数D取模,将所得答案插入到数列

HDU 1754 I Hate It(线段树之单点更新,区间最值)

I Hate It Time Limit: 9000/3000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others) Total Submission(s): 70863    Accepted Submission(s): 27424 Problem Description 很多学校流行一种比较的习惯.老师们很喜欢询问,从某某到某某当中,分数最高的是多少. 这让很多学生很反感.不管你喜不喜欢,现在需要你做的是,就是按照老师的

线段树入门总结

线段树的入门级 总结   线段树是一种二叉搜索树,与区间树相似,它将一个区间划分成一些单元区间,每个单元区间对应线段树中的一个叶结点.      对于线段树中的每一个非叶子节点[a,b],它的左儿子表示的区间为[a,(a+b)/2],右儿子表示的区间为[(a+b)/2+1,b].因此线段树是平衡二叉树,最后的子节点数目为N,即整个线段区间的长度.      使用线段树可以快速的查找某一个节点在若干条线段中出现的次数,时间复杂度为O(logN).而未优化的空间复杂度为2N,因此有时需要离散化让空间

[bzoj3932][CQOI2015]任务查询系统-题解[主席树][权值线段树]

Description 最近实验室正在为其管理的超级计算机编制一套任务管理系统,而你被安排完成其中的查询部分.超级计算机中的 任务用三元组(Si,Ei,Pi)描述,(Si,Ei,Pi)表示任务从第Si秒开始,在第Ei秒后结束(第Si秒和Ei秒任务也在运行 ),其优先级为Pi.同一时间可能有多个任务同时执行,它们的优先级可能相同,也可能不同.调度系统会经常向 查询系统询问,第Xi秒正在运行的任务中,优先级最小的Ki个任务(即将任务按照优先级从小到大排序后取前Ki个 )的优先级之和是多少.特别的,如