This is a hard version of the problem. The only difference between an easy and a hard version is in the number of queries.
Polycarp grew a tree from n vertices. We remind you that a tree of n vertices is an undirected connected graph of n vertices and n−1 edges that does not contain cycles.
He calls a set of vertices passable if there is such a path in the tree that passes through each vertex of this set without passing through any edge twice. The path can visit other vertices (not from this set).
In other words, a set of vertices is called passable if there is a simple path that passes through all the vertices of this set (and possibly some other).
For example, for a tree below sets {3,2,5},{1,5,4},{1,4} are passable, and {1,3,5},{1,2,3,4,5} are not.
题目大意
给定一颗 n 个节点的树,进行 q 次查询。每次查询输入 k 的节点编号,问这 k 个节点在树上是否能构成一条链。
思路
如果 k 个节点能连成一条链,那么在树上就能找得一个点 r,使得剩下的点 r 要么在左边,要么在右边子树的某一条链上。由此可见,需要大量进行“求树上两个点的最近公共祖先运算”,观察数据规模,每次运算如果使用朴素的 O(n) 算法,会超时。因此需要采用 LCA 倍增的算法将查询时间降低为 O(logn)。