The longest Path#11452

The longest Path (Editoryal)

Let's find a topological sort of the graph. Denote by the maximum number of cities that can be visited along a path starting from vertex .

Consider the vertices in the order of the topological sort. Let be the current vertex. Let v_1, v_2, ..., v_k be the vertices to which edges go from . Then update the value as follows:

dp[u] = max(dp[v_i] + 1), 1 \le i \le k

Initially, set dp[u] = 0~(1 \le u \le n).

After processing all the vertices, find the greatest value in the array. It equals the length of the longest path in the graph.

Example

On the left is the graph from the first example. On the right is the one from the second example. The longest paths are highlighted.

In the first example, the longest path equals dp_1 = 3.

In the second example, the longest path equals dp_4 = 2.

Algorithm implementation

Let's declare the adjacency list of the graph .

vector<vector<int> > g;

The function dfs performs a depth-first search starting from vertex . We topologically sort the vertices of the graph and store them in the array .

void dfs(int v)
{
  used[v] = 1;
  for (int to : g[v])
    if (used[to] == 0) dfs(to);
  top.push_back(v);
}

The main part of the program. Read the input data. Bild the adjacency list of the directed graph.

scanf("%d %d", &n, &m);
g.resize(n + 1);
while (m--)
{
  scanf("%d %d", &a, &b);
  g[a].push_back(b);
}

Run a depth-first search on the disconnected graph.

used.resize(n + 1);
for (i = 1; i <= n; i++)
  if (used[i] == 0) dfs(i);

Iterate over the vertices of the graph in the order opposite to their topological sort, that is, we iterate over the vertices in the array from left to right.

dp.resize(n + 1);
for (int u : top)
{

A path from vertex to itself has length (initialization).

  dp[u] = 0;

Iterate over the vertices adjacent to . Consider the edge .

  for (int v : g[u])

For all such vertices , find the maximum among the values dp[v] + 1.

    dp[u] = max(dp[u], dp[v] + 1);
}

Find and print the largest element in the array. It corresponds to the length of the longest path in the graph.

res = *max_element(dp.begin(), dp.end());
printf("%d\n", res);