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.
№ | Пользователь | Рейтинг |
---|---|---|
1 | tourist | 4009 |
2 | jiangly | 3831 |
3 | Radewoosh | 3646 |
4 | jqdai0815 | 3620 |
4 | Benq | 3620 |
6 | orzdevinwang | 3529 |
7 | ecnerwala | 3446 |
8 | Um_nik | 3396 |
9 | gamegame | 3386 |
10 | ksun48 | 3373 |
Страны | Города | Организации | Всё → |
№ | Пользователь | Вклад |
---|---|---|
1 | cry | 164 |
1 | maomao90 | 164 |
3 | Um_nik | 163 |
4 | atcoder_official | 160 |
5 | -is-this-fft- | 158 |
6 | awoo | 157 |
7 | adamant | 156 |
8 | TheScrasse | 154 |
8 | nor | 154 |
10 | Dominater069 | 153 |
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.
Название |
---|
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).
can you just share the implement part of reverse going in dp[u]-1 --> dp[u]-2 -->0
You can practice the same concept on atcoder — https://atcoder.jp/contests/dp/tasks/dp_g