Help with the approach and code in C++. Thanks I have tried Dijkstra by make every edge weights to -1. But I am not able to print the longest path.

# | User | Rating |
---|---|---|

1 | tourist | 3565 |

2 | Benq | 3540 |

3 | Petr | 3519 |

4 | maroonrk | 3503 |

5 | jiangly | 3391 |

6 | ecnerwala | 3363 |

7 | Radewoosh | 3349 |

8 | scott_wu | 3313 |

9 | ainta | 3298 |

10 | boboniu | 3289 |

# | User | Contrib. |
---|---|---|

1 | 1-gon | 198 |

2 | Errichto | 195 |

3 | rng_58 | 190 |

4 | awoo | 186 |

5 | SecondThread | 185 |

6 | Um_nik | 182 |

7 | vovuh | 177 |

8 | Ashishgup | 176 |

9 | antontrygubO_o | 174 |

10 | -is-this-fft- | 173 |

Help with the approach and code in C++. Thanks I have tried Dijkstra by make every edge weights to -1. But I am not able to print the longest path.

↑

↓

Codeforces (c) Copyright 2010-2021 Mike Mirzayanov

The only programming contests Web 2.0 platform

Server time: Mar/07/2021 05:56:27 (g1).

Desktop version, switch to mobile version.

Supported by

User lists

Name |
---|

Naive approach : Do BFS from every non visited node and keep track of farthest node which is reachable (let's say it's pathlength as COUNT) & mark every intermediate node visited. take maximum of all COUNT and print path from node(which is giving max COUNT) to Farthest node. I think it should work :)

Find a topological sort of the given graph and do dp on it. dp[u] is the length of the longest path which ends in node u. Initially dp[u] = 0 for every u. To calculate this dp go from left to right in topological order and if the current node is u, for every node v such that there is edge from u to v dp[v] = max(dp[v], dp[u] + 1). Then the length of the longest path in the graph is the maximal element in the dp array. To restore the longest path find any u such that dp[u] = max and go through reverse edges of the graph to any v such that dp[v] = dp[u] — 1, until dp[u] is not zero and add u to your answer array. Reverse the answer and it will be one of the possible longest paths in the given DAG. Complexity is O(N + M).

Hi, Thanks got it

You can practice the same concept on atcoder — https://atcoder.jp/contests/dp/tasks/dp_g

do simple dfs on nodes and store longest path in a dp

Spoiler...import sys sys.setrecursionlimit(10**9)

def dfs (edges , e , visited ,dp): visited[e] = True for i in edges[e]: if not visited[i]: dfs(edges,i,visited,dp) dp[e] = max(dp[e],dp[i]+1) return dp[e]

n,m = map(int, input().split()) edges = [[] for i in range(n + 1)] for i in range(m): u,v = map(int, input().split()) edges[u].append(v) dp = [0] * (n + 1) visited = [False] * (n + 1) for i in range(1,n+1): if not visited[i]: dp[i] = dfs(edges,i,visited,dp) if len(dp) > 0 : print(max(dp)) else : print(0)