Can anyone help me out with this problem, I looked up on many places but couldn't find any satisfactory solution
# | User | Rating |
---|---|---|
1 | tourist | 3751 |
2 | Benq | 3727 |
3 | cnnfls_csy | 3691 |
4 | Radewoosh | 3651 |
5 | jiangly | 3632 |
6 | orzdevinwang | 3559 |
7 | -0.5 | 3545 |
8 | inaFSTream | 3478 |
9 | fantasy | 3468 |
10 | Rebelz | 3415 |
# | User | Contrib. |
---|---|---|
1 | adamant | 178 |
2 | awoo | 167 |
3 | BledDest | 165 |
4 | Um_nik | 164 |
5 | maroonrk | 163 |
6 | SecondThread | 160 |
7 | nor | 157 |
8 | -is-this-fft- | 154 |
9 | kostka | 146 |
10 | Geothermal | 143 |
Can anyone help me out with this problem, I looked up on many places but couldn't find any satisfactory solution
Name |
---|
you can just simply search for cycle in undirected graph and keep a parent array if you find cycle just backtrack using parent array
tried that but it fails in the case my dfs starting point is in the cycle as it would have no parent
Once you reach an already visited node X which isn't the parent keep pushing parent-nodes into vector until you reach X Then terminate the dfs and print the ans
To solve the problem, you just need to look for any cycle in the graph. To do this, you can perform a dfs and keep track of the tree it generates using an array of parents, where $$$parent[v] = u$$$ if $$$v$$$ is a direct descendant of $$$u$$$, and for the root node, you can set $$$parent[root] = -1$$$.
Suppose we are at node $$$u$$$, and let $$$v$$$ be a direct child of $$$u$$$. Then there exists a cycle if $$$v$$$ has a $$$backedge$$$ with an ancestor node of $$$u$$$ in the DFS tree, or if $$$v$$$ has a descendant node that has a $$$backedge$$$ with an ancestor node of $$$u$$$.
Let $$$v$$$ be the node with a $$$backedge$$$ to $$$w$$$ ancestor of $$$u$$$. Therefore, we can traverse in reverse order from $$$v$$$ to $$$w$$$ using the parent array and construct an array $$$ans$$$ composed by $$$[w, ..., u, v,w]$$$, which would be our cycle.
Time Complexity: $$$O(n + m)$$$
thanks man