线段树 自己总结的模板
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);
}
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);
}
相关文章推荐
- 自己总结的 Makefile 小模板
- 线段树总结 与 模板
- 模板整理(总结别人的及自己的,每周更新)
- 线段树模板(学长给的,自己消化了一下,其实基本上差不多(好吧,一模一样QAQ))
- 线段树 + 树状数组 【模板总结】
- ZKW线段树模板总结
- Discuz学习总结——自己写模板
- 线段树---分析 &amp;&amp; 模板总结
- HDU 4819 Mosaic(二维线段树单点更新+区间查询+自己的写法模板)
- 总结自己的经验,打造自己的设计模式
- [导入]自己总结的常用ORACLE Text 文本检索
- 自己写的一个简陋的C++队列模板
- 写给自己看的,理解J2EE,总结自己的学习
- 开发中碰到过的一些问题总结,给自己也给大家一个参考!
- 链表处理函数(自己总结)
- 常用的一些技术词汇对照(自己总结)
- 读RTL8139驱动自己的总结(PCI相关)
- 总结一下04-05赛季,在顺境中迷失了自己。快点找回我!
- fwrite的用法和main参数的使用方法(自己的总结)