mkitkat's blog

By mkitkat, history, 5 years ago, In English

I can't understand the solutions of Query on trees https://www.codechef.com/COMA2020/problems/QUERYT . Help me with the concept and Solution.

Question: You are given a tree with N nodes and N−1 edges. The nodes are numbered from 1 to N and the tree is rooted at 1.

Every node has a value associated with it.

If we consider the simple path between two nodes u and v , then a node in this path is called special if it's value is not coprime with the value of lca(u,v). Here lca(u,v) means the lowest common ancestor of u and v.

You will be given Q queries. Every query contains two integers denoting two nodes,u and v. You have to find the count of special nodes in the simple path between u and v.

  • Vote: I like it
  • +5
  • Vote: I do not like it

| Write comment?
»
5 years ago, # |
  Vote: I like it 0 Vote: I do not like it
The key is in the constraints: val[i] <= 200.
let good(x, y) be true if x and y are not coprime.
let dp[x][u] be the sum of good(x, val[v]) where v is any node in the path from the root to node u (v is an ancestor of u).
You can build the array dp in O(max(val[i]) * N) by running a dfs for each possible value x (from 1 to 200).
Given a query (u, v), let x be val[lca(u, v)]. so the answer is:
dp[x][u] + dp[x][v] - dp[x][lca] - dp[x][parent of lca]
The time complexity of the solution is O(max(val[i]) * N + (N + Q) * log N) (if you use a O(log N) algorithm to calculate the lca)