Simple segment tree merge

understanding

As the name implies, it is to merge the information of the two line segment trees.

Violent merging is a good idea. Just traverse the two trees together. ComplexityO (n)

But in many cases, we need to merge two line segment trees that are not full (here, "not full" means that some intervals have not been used at all), and space and time are not enough.

So some optimizations are used.

Ideas

How to optimize the space? Very simple, dynamic opening point.

(I won’t open the link here, just open it dynamically, and skip it if you understand:

In fact, it is to record the left and right sons of each node (no longer use id*2, id*2+1 to access directly), the initial value is zero, when it needs to be inserted down, it is assigned to two new points (referred to as opening points) , There is no need to open the query, just a special judgment

Done)

After using the dynamic opening point, you then merge with brute force traversal:

inline int mergg(int x,int y,int l,int r){
	if(!x||!y)return x|y; //两节点其中一个为零,另一个补上去
	int mid=(l+r)>>1;
	t[x].ls=mergg(t[x].ls,t[y].ls,l,mid),t[y].ls=0; //合并左子树
	t[x].rs=mergg(t[x].rs,t[y].rs,mid+1,r),t[y].rs=0; //合并右子树
	.../*此处合并两点信息*/
	return x;
}

Although it still seems O(n), (in most problems) when the total size of the merged tree is limited, the total complexity is much faster O (nlogn)than the non-dynamic one O (n ^ 2).

Example question: ZZH travel

Guess you like

Origin blog.csdn.net/weixin_43960287/article/details/110474047