I am trying to solve this problem for a while now but I can't come up with solution better than SPFA from every node which (for sure) gives TLE. so can you help finding a faster solution? thanks in advance.
# | User | Rating |
---|---|---|
1 | tourist | 3856 |
2 | jiangly | 3747 |
3 | orzdevinwang | 3706 |
4 | jqdai0815 | 3682 |
5 | ksun48 | 3591 |
6 | gamegame | 3477 |
7 | Benq | 3468 |
8 | Radewoosh | 3462 |
9 | ecnerwala | 3451 |
10 | heuristica | 3431 |
# | User | Contrib. |
---|---|---|
1 | cry | 167 |
2 | -is-this-fft- | 162 |
3 | Dominater069 | 160 |
4 | Um_nik | 158 |
5 | atcoder_official | 157 |
6 | Qingyu | 156 |
7 | adamant | 151 |
7 | djm03178 | 151 |
7 | luogu_official | 151 |
10 | awoo | 146 |
I am trying to solve this problem for a while now but I can't come up with solution better than SPFA from every node which (for sure) gives TLE. so can you help finding a faster solution? thanks in advance.
Name |
---|
Bellman-Ford?
SPFA is faster than Bellman-ford and it gives TLE :(
actually SPFA is an improvement of the Bellman–Ford algorithm
Oh, I see. I think I read the problem wrong.
Another idea: Assuming d[u][v] <= d[u][w] + d[w][v] holds, we can simply do a Bellman-Ford (or SPFA if you want) from vertex 1 to all other vertices in O(nm) and find pairs of distances in O(n^2) since we can rearrange the inequality to be d[w][v] >= d[u][v] — d[u][w], therefore all of the answers we gathered are valid. I'm guessing the condition still holds under negative edge weights as well, after you've removed the possibility of a negative cycle.
I'm sorry but I can't get your idea well.How doing Bellman-ford only from vertex 1 will guarantee finding the answer.
The answer is not going to be <insert shortest paths algorithm here>, that would be boring.
Maybe this gives TLE but here is what I would do. First, let's check if there is a negative cycle. If so, output
-inf
. Now, letdp[u]
denote the length of the shortest path that ends with the vertexu
. To calculatedp[u]
we do this:Now, output the minimum of
dp[u]
over all verticesu
.thanks this is very nice approach actually. I think you may want to add
dp[v] = min(dp[v], cost(u, v))
first. any way I got the idea thanks alot.