hackerEarth Problem - Largest Cycle In A tree
We are given a tree of N nodes and N - 1 edges. We have to find out two nodes
in the tree such that if we add an edge between them then we get a large cycle
with a maximum no of nodes as shown below.
For the above tree, adding an edge between nodes 10 and 16 creates a big
cycle. We can find these two nodes in two different ways.
We'll try to find the furthest node from the root node first, and then the
furthest node from the previous furthest node in the second attempt. Those two
farthest nodes will lead to our correct solution.
Solution in Kotlin code
import java.util.* fun main() { var total = 0 var furthest = -1 val scan = Scanner(System.`in`) val N = scan.nextInt() // one space extra because of zero val tree = Array<ArrayList<Int>>(N + 1) { ArrayList() } val vis = Array(tree.size) { false } repeat(N - 1) { val a = scan.nextInt() val b = scan.nextInt() tree[a].add(b) tree[b].add(a) } fun dfs(src: Int, len: Int) { val S = Stack<Int>() vis[src] = true S.push(src) while (S.isEmpty().not()) { val top = S.peek() for (node in tree[top]) { if (vis[node].not()) { S.push(node) vis[node] = true break } } if (top == S.peek()) { if (S.size > total) { total = S.size furthest = top } S.pop() } } } dfs(1, 1) vis.fill(false) val a = furthest total = 0 dfs(a, 1) println("$a $furthest") }