Блог пользователя aviator_012

Автор aviator_012, история, 4 года назад, По-английски

I found an interesting problem on the tree in google's online assessment. You have been given a Tree consisting of N nodes, and an array V of length N presents the value of ith Node — V[i]. You have to find the number of distinct paths of length greater than one where the value of the starting node equals the value of the ending node. And all the node values between starting and ending nodes should be less than or equal to the value of starting node.

constraints:
1<= N <= 100000

Sample input:
N = 5
edges = [{1,2}, {1,3}, {3, 4}, {3, 5}]
V = [2, 3, 1, 2, 3]

Output:
2

explanation:
path = 1-3-4
path = 2-1-3-5

I was able to come up with a solution with a time complexity of O(N^3). I was wondering how to solve this efficiently.

  • Проголосовать: нравится
  • +31
  • Проголосовать: не нравится

»
4 года назад, скрыть # |
← Rev. 2  
Проголосовать: нравится 0 Проголосовать: не нравится

Hint: disjoint set union.

  • »
    »
    4 года назад, скрыть # ^ |
    ← Rev. 2  
    Проголосовать: нравится +25 Проголосовать: не нравится
    Spoiler
»
4 года назад, скрыть # |
 
Проголосовать: нравится +30 Проголосовать: не нравится

Consider a node $$$ u $$$ , find the farthest ancestor $$$ p $$$ such that the path from $$$ u $$$ to $$$ p $$$ contains values $$$ \lt =A[u] $$$. Compute this for all nodes $$$ u $$$ in the tree . Now for any pair $$$(u,v)$$$ to form special path obviously $$$ A[u] == A[v] $$$ and they must have this common farthest ancestor described above (You can check all cases when $$$(u,v)$$$ form the answer they have same common farthest ancestor). Now for each node assuming it to be the farthest ancestor compute the count of nodes having same value , let it be $$$ C $$$ , increment the answer by $$$ C*(C-1)/2 $$$. Attaching the implementation of above approach : https://pastebin.com/TGcDtBpK `