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 | 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 | 160 |
5 | djm03178 | 158 |
5 | -is-this-fft- | 158 |
7 | adamant | 155 |
8 | Dominater069 | 154 |
9 | awoo | 152 |
10 | luogu_official | 150 |
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.