Query whether path between two nodes in a tree contains a given value

六眼飞鱼酱① 提交于 2020-01-24 02:03:25

问题


Suppose a tree has N nodes connected by N-1 edges, where 1 < N < 10^5. The nodes are numbered from 1 to N, and each node holds a value, which is also number in the range 1 to N; the values are unrelated to the node numbers, and are not necessarily distinct. The tree is not necessarily balanced.

Because it is a tree, we know there is only one path between any two nodes.

Then, we are given M queries, where 1 < M < 10^5. Each query gives two nodes, A and B, and a value T. For each query we have to figure out if there is a node with that value T in the path between A and B (including the values at A and B).

My first thought was for every query, to do a breadth-first search from A to find the path to B. While you are doing that, I would keep track of all the values I encountered along the way, and would answer in this manner. But this doesn't work as it takes O(NM) time, which is on the order of 10^10, so it doesn't finish in time. The solution must run in under 4 seconds.

Is there a faster way to solve this problem, or am I approaching this the wrong way?

EDIT: I had the idea to use segment trees. I know that they are more commonly used for range queries, but perhaps I could manipulate them to work for this question?

来源:https://stackoverflow.com/questions/59331956/query-whether-path-between-two-nodes-in-a-tree-contains-a-given-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!