GCD Path on a Tree

4.5

2 votes
Algorithms, Depth First Search, Dynamic programming, Graphs, Medium
Problem

Given an Integer K and a tree of N vertices where each vertex consists of a value Vi 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×K vertices in the path and Xi be the value associated with ith vertex in that path, then gcd(Xi×K+1, Xi×K+2, Xi×K+3, ... Xi×K+K)>1 i[0,L1]. 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 N1 lines consists of two integers ui and vi representing an edge between ui and vi.
Next line consists of N space separated integers where ith of them is the value Vi associated to ith vertex.

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

Constraints

  • 1N105
  • 1Kmin(N,10)
  • 1Vi106
Time Limit: 2
Memory Limit: 256
Source Limit:
Explanation

Longest Path is 432678 of length 6
gcd(V4,V3)=gcd(30,5)=5>1
gcd(V2,V6)=gcd(9,21)=3>1
gcd(V7,V8)=gcd(6,3)=3>1

Editor Image

?