GCD Path on a Tree
Practice
4.5 (2 votes)
Algorithms
Depth first search
Dynamic programming
Graphs
Medium
Problem
81% Success 4104 Attempts 50 Points 2s Time Limit 256MB Memory 1024 KB Max Code

Given an Integer K and a tree of N vertices where each vertex consists of a value \(V_i\) associated to it. Find the longest path in the tree which satisfies the following conditions

  1. The number of vertices in the path should be a multiple of K.
  2. Let's say there are \(L \times K\) vertices in the path and \(X_i\) be the value associated with \(i^{th}\) vertex in that path, then \(gcd( X_{i \times K+1}\), \(X_{i \times K+2}\), \(X_{i \times K+3}\), ... \(X_{i \times K+K}) > 1\) \(\forall i \in [0, L-1].\) where \(gcd(x1, x2 ... xn)\) is the Greatest Common Divisor of the numbers \(x1,x2... xn\).

Input Format
First line consists of two integers N and K.
Next \(N-1\) lines consists of two integers \(u_i\) and \(v_i\) representing an edge between \(u_i\) and \(v_i\).
Next line consists of N space separated integers where \(i^{th}\) of them is the value \(V_i\) associated to \(i^{th}\) vertex.

Output Format
Print an Integer representing the longest path as described in the problem statement.

Constraints

  • \(1 \le N \le 10^5\)
  • \(1 \le K \le min(N,10)\)
  • \(1 \le V_i \le 10^6\)

Please login to use the editor

You need to be logged in to access the code editor

Loading...

Please wait while we load the editor

Loading...
Results
Custom Input
Run your code to see the output
Submissions
Please login to view your submissions
Similar Problems
Points:50
3 votes
Tags:
AlgorithmsApprovedGraphsMediumTrees
Points:50
3 votes
Tags:
GraphsAlgorithmsDepth First Search
Points:50
Tags:
Depth First SearchFenwick TreeGraphsMediumNumber TheoryPrime Factorization