线段树 自己总结的模板

来源:互联网 发布:java优缺点 编辑:程序博客网 时间:2024/05/17 03:46

struct treeNode {

    int start;

    int end;

    int cover;        // 覆盖标记 -1:未覆盖  0:部分覆盖  1:完全覆盖

    treeNode *left;

    treeNode *right;

    treeNode *parent;

};


//构造线段树函数

treeNode *createTree(int start,int end)

{

    treeNode * p =new treeNode();

    if (end-start==1) {

        returnNULL;

    }

    p->start = start;

    p->end=end;

    p->cover=-1;

    p->parent=NULL;

    // 生成左子树

    p->left=createTree(start, (start+end)/2);

    p->left->parent=p;

    // 生生右子树

    p->right=createTree((start+end)/2, end);

    p->right->parent=p;

    return p;

}


//覆盖线段树函数

void coverTree(treeNode* p,int start,int end)

{

    if (p->cover==1)return;

    //完全覆盖

    if (start==p->start&&end==p->end) {

        p->cover=1;

        //父段存在的话,回溯、重新判断覆盖情况

        treeNode *temp = p;

        while (temp->parent!=NULL) {

            if (temp->parent->cover==-1) temp->parent->cover=0;

            if (temp->parent->cover==0)  temp->parent->cover=1;

            temp=temp->parent;

                

        }

        //按照我的设计,根结点的parentNULL

        if (temp->cover==-1) temp->cover=0;

        if (temp->cover==0)  temp->cover=1;

    }

    if (end <= (p->start+p->end)/2) {//向左子树覆盖

        coverTree(p->left, start, end);

    }

    else if (start  >=(p->start+p->end)/2)//向右子树覆盖

    {

        coverTree(p->right, start, end);

    }

    else{                                  //向左、右子树覆盖

        //先向左子树覆盖

        coverTree(p->left, start, (p->start+p->end)/2);

        //向右子树覆盖

        coverTree(p->right, (p->start+p->end)/2, end);

        

    }


原创粉丝点击