algorithm - weight sum for path between two nodes in a tree -


you given tree n vertices. every node has integer weight associated it. there huge number of queries(~n^2) on given tree. query (a, b), a, b 2 vertices of tree, need calculate sum of weights of nodes on unique path b, including , b.

i can dfs/bfs individual queries going take o(n^3) ~n^2 possible queries.. can suggest better takes less o(n) per query?

thanks..

if tree not rooted, make arbitrary node root of tree.

we'll denote weight of node x w[x] , sum of weights of nodes root node x c[x].

now let's assume there's query like, u, v:

we've find lowest common ancestor of node u , v. let's assume lca of u , v p. result query (u,v) c[u]-c[p]+c[v]-c[p]+w[p]


Comments

Popular posts from this blog

basic authentication with http post params android -

vb.net - Virtual Keyboard commands -

css - Firefox for ubuntu renders wrong colors -