其他分享
首页 > 其他分享> > zkw树

zkw树

作者:互联网

https://sshwy.gitee.io/2018/10/01/55406/
https://www.cnblogs.com/Judge/p/9514862.html
https://blog.csdn.net/DREAM_yao/article/details/108801613

#include<vector>
#include<iostream>
#include<math.h>
#include<limits.h>
using namespace std;

class segmenttree
{
	struct node
	{
		int max;
		bool lazy;
		node(int _max, bool _lazy):max(_max),lazy(_lazy){};
	};
	vector<node>tree;
	int start;
public:
	int query(int left, int right);
	segmenttree(vector<int>&array)
	{
		int h = (int)ceil(log(array.size()/log(2))) + 1;///<线段树的曾数
		start = (1<<(h-1)) - 1;///<叶节点的开始
		int n = (1<<h)-1;///<线段树的节点个数
		vector<node>a(n,node(-1,false));
		tree = a;
		for(size_t i=0;i<array.size();++i)
			tree[start+i]=node(array[i], true);
		for(int i=start>>1;; i>>=1)///<树的曾数
		{	
			for(int j=0; j<i*2+1; ++j)///<横行
			{	
				node leftNode = tree[2*(i+j)+1];
				node rightNode = tree[2*(i+j)+2];
				if(leftNode.lazy && rightNode.lazy)
					tree[i+j] = node(max(leftNode.max, rightNode.max), true);
				else if(leftNode.lazy && !rightNode.lazy)
					tree[i+j] = leftNode;
			}
			if(0==i)///<i=0得进来一次
				break;
		}	
		return; 
	}
};

int segmenttree::query(int left, int right)
{
	int mmax = max(tree[left].max, tree[right].max);
	left+=start;
	right+=start;
	for(;;left=(left-1)>>1,right=(right-1)>>1)
	{	if(0==left)
		{
			mmax = max(mmax, tree[left].max);
			break;
		}
		///<对于left而言,右子节点在区间内。right的左子节点在区间内
		if(1==left%2) ///<奇数是左子节点,偶数是右子节点
			mmax = max(mmax, tree[left+1].max);
		if(0==right%2)
			mmax = max(mmax, tree[right-1].max);
	}
	return mmax;
}

int main(void)
{
	vector<int>a={1,4,6,8,4,0,9};
	segmenttree b(a);
	cout<<b.query(1,6)<<endl;
	return 0;
}

标签:lazy,include,int,max,right,https,zkw
来源: https://blog.csdn.net/qigezuishuaide/article/details/111879595