I haven't done any questions for two days. There are so many things to do during the Chinese New Year. Today, I have to do one question anyway.
This question is the shortest path of a single source node. When I first thought of dijskraAlgorithmBecause the data size is large and the result of the neighboring table has timed out, the first time an error is submitted, because I did not notice that the edge is bidirectional, e should be twice the size of M.
So spfa and AC are used.
Because there are too many vertices and edges, the D algorithm times out. Normally, the time complexity of the D algorithm is N * n, and the S algorithm is M * n, I thought it would be better to use D, but because it is an adjacent table that records edges, in this case, the D algorithm needs to be optimized because all edges will be traversed twice, at this time, the time is obviously greater than the S algorithm.
I see on the Internet, some people are using dij and the combination of priority queue, blog http://www.cnblogs.com/Yu2012/archive/2011/11/29/2268442.html
Below is the ACCode:
# Include <cstdio> # include <queue> # include <cstring> using namespace STD; const int n = 20010; const int M = 50010; struct edge {int from,, w, next;} e [M * 2]; int icase, n, m, S, T, idx, head [N]; void add (int u, int V, int W) {e [idx]. next = head [u]; E [idx]. from = u, E [idx]. to = V, E [idx]. W = W; head [u] = idx ++; E [idx]. next = head [v]; E [idx]. from = V, E [idx]. to = u, E [idx]. W = W; head [v] = idx ++;} int Spfa () {queue <int> q; bool vis [N]; memset (VIS, 0, sizeof (VIS); q. push (s); int d [N]; for (INT I = 0; I <n ;+++ I) d [I] = 500000000; d [s] = 0; while (! Q. empty () {int u = Q. front (); q. pop (); vis [u] = 0; For (INT I = head [u]; I! =-1; I = E [I]. next) {int v = E [I]. to, W = E [I]. w; If (d [v]> d [u] + W) {d [v] = d [u] + W; If (! Vis [v]) {q. push (V); vis [v] = 1 ;}}} return d [T] ;}int main () {scanf ("% d", & icase ); int T = 1; while (icase --) {scanf ("% d", & N, & M, & S, & T ); idx = 0; For (INT I = 0; I <n; ++ I) head [I] =-1; for (INT I = 0; I <m; ++ I) {int from, to, W; scanf ("% d", & from, & to, & W); add (from,, w);} int ans = spfa (); printf ("case # % d:", t ++); If (ANS <500000000) printf ("% d \ n", ANS); else printf ("unreachable \ n ");}}