We can solve above problem in O(V+E) time if the given graph is directed instead of undirected graph. Below are steps.

1) Create a distance array dist[] and initialize all entries of it as minus infinite2) Order all vertices in toplogical order.3) Do following for every vertex u in topological order.…..Do following for every adjacent vertex v of u………..if (dist[v] < dist[u] + weight(u, v))……………dist[v] = dist[u] + weight(u, v)4) Return maximum value from dist[]

Since there is no negative weight, processing vertices in topological order would always produce an array of longest paths dist[] such that dist[u] indicates longest path ending at vertex ‘u’.

The implementation of above approach can be easily adopted from here. The differences here are, there are no negative weight edges and we need overall longest path (not longest paths from a source vertex). Finally we return maximum of all values in dist[].

Time Complexity : O(V + E)

We create undirected graph for given city map and do DFS from every city to find maximum length of cable. While traversing, we look for total cable length to reach the current city and if it’s adjacent city is not visited then call DFS for it but if all adjacent cities are visited for current node, then update the value of max_length if previous value of max_length is less than current value of total cable length.