您的位置:首页 > 其它

线段树 自己总结的模板

2017-06-03 10:58 465 查看
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) {

        return
NULL;

    }

    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;

                

        }

        //按照我的设计,根结点的parent为NULL

        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);

        

    }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  线段树