Please help me with this problem: Given an undirected weighted graph have n vertices and m edges (n <= 1000, m <= 10000). How to check if there exists a simple cycle have total weight >= 0. Thanks for your help.
# | User | Rating |
---|---|---|
1 | tourist | 3985 |
2 | jiangly | 3814 |
3 | jqdai0815 | 3682 |
4 | Benq | 3529 |
5 | orzdevinwang | 3526 |
6 | ksun48 | 3517 |
7 | Radewoosh | 3410 |
8 | hos.lyric | 3399 |
9 | ecnerwala | 3392 |
9 | Um_nik | 3392 |
# | User | Contrib. |
---|---|---|
1 | cry | 169 |
2 | maomao90 | 162 |
2 | Um_nik | 162 |
4 | atcoder_official | 161 |
5 | djm03178 | 158 |
6 | -is-this-fft- | 157 |
7 | adamant | 155 |
8 | awoo | 154 |
8 | Dominater069 | 154 |
10 | luogu_official | 151 |
Please help me with this problem: Given an undirected weighted graph have n vertices and m edges (n <= 1000, m <= 10000). How to check if there exists a simple cycle have total weight >= 0. Thanks for your help.
Name |
---|
You can multiply each edge weight by $$$-1$$$. Then use Bellman Ford's algorithm to find a negative cycle which iirc works in $$$O(n^2 + n \cdot m)$$$.
But as far as I know, it can only be used for directed graph. When use it in undirected graph, this algorithm can go on a loop in a negative weighted edge (cycle of length 2) but it not simple cycle.
Not sure. There's another approach you can try. It has an $$$O(m^2)$$$ complexity so not sure if it will pass. For eaxh edge from node $$$a$$$ to node $$$b$$$ with weight $$$w$$$, "remove" that edge, then find the shortest distance between $$$a$$$ and $$$b$$$ (assuming there is indeed a path between these after removing the edge). Let the distance found be $$$p$$$. You have a cycle with weight $$$p+w$$$.
But how can we find the shortest distance between a and b ? It still can go on a loop in a negative weighted edge.
Can someone help me please. I still can't solve this problem.
Sorry I forgot to reply back. You can use modified Bellman Ford's: keep track of the node used to relax the distance for every node, this way you can avoid 2 node cycles.
problem link??
I think you can use Bellman Ford's algorithm but with vertices {vertex, last edge}, and then you update distance only if new edge is not equal to the last edge used. I think it will still be O(m^2) because every edge creates only 2 new vertices.