1

I got a question in a contest(which is ended weeks ago). The question as I interpreted was -:

Given an undirected acyclic graph which is connected by (N-1) edges and N nodes. The graph is guaranteed to be connected. Given two nodes u and v, you have to find two nodes x and y of the graph such that the path between these two nodes overlaps the path between the given cities u and v completely and gcd(x, y) is maximum possible.

Constraints

1 <= N <= 5 * 10^5

1 <= a,b,u,v <= N

where a,b are the two arbitrary nodes in the graph.

Example let the graph has 10 nodes (1 to 10)

Now in preceeding line I will give two integers a and b which means a and b are directly connected.

1 4

1 5

1 2

4 3

4 6

5 7

2 10

2 9

2 8

At last u v 4 2

Ans - 4

The path from u to v is 4 -> 1 -> 2

Now, some of the paths which completely ovelaps the path from u to v are:

4 -> 1 -> 2 -> 10

3 -> 4 -> 1 -> 2 -> 9

4 -> 1 -> 2 -> 8

and so on....

Note that, selecting the path from 4 to 8 completely overlaps path u to v and also gcd(4,8) = 4 which is the maximum possible.

The graph is : https://i.stack.imgur.com/Phkwi.png Graph Time Limit: 3.0 sec

My approach for solving the problem was :

Find the path from each node to every other node and store it in list of arrays.

Iterate over all lists and find whether u and v path is contained in the array.

If the path is found and calculate the gcd of starting and ending node and check for the max gcd.

However I think my approach is too brute force and code is too long and I think it has too much complexity.

Can anyone suggest any suggestion or approach to tackle this question?

Brij Raj Kishore
  • 1,595
  • 1
  • 11
  • 24

1 Answers1

0

Maybe you can do a dfs on the starting and ending vertex and from those vertices remove the ones already on the sub graph. Now you have all the possible vertices which can be part of the solution. Check all possible combinations from those vertices and select the pair with maximum gcd. During the dfs make sure to add a if condition to ignore the vertex connceted to it so that on each side of the sub path you only get the vertices which are not part of the sub path

Sanath Kumar
  • 163
  • 1
  • 12