# Include <iostream>
# Include <vector>
# Include <set>
Using namespace STD;
Typedef vector <int> VI;
Typedef pair <int, int> II;
Typedef vector <II> VII;
Typedef vector <VII> vvii;
Const int INF = 0x7fffffff;
// Create an authorized list (For details, refer to the example. You may need to modify the list, especially for undirected graphs)
// N indicates the number of vertices (marked from 0) and E indicates the number of edges.
Vvii avlmaker (int n, int e)
{
Vvii g (N );
For (INT I = 0; I <E; I ++)
{
Int V1, V2, D;
Cin> V1> V2> D;
G [V1]. push_back (II (V2, d ));
}
Return g;
}
// S is the source point, and returns the shortest length from S to each point. inf indicates that it cannot be reached.
VI Dijkstra (const vvii & G, int s) // vvii G is the adjacent vertices list of the weighted directed graph
{
Int n = G. Size ();
Vi d (n, INF );
Set <II> q;
D [s] = 0;
Q. insert (II (0, s ));
While (! Q. Empty ())
{
Ii p = * q. Begin ();
Q. Erase (Q. Begin ());
Int d = P. First, V = P. Second;
For (INT I = 0, j = G [v]. Size (); I <j; I ++)
{
Int v2 = G [v] [I]. First, D = G [v] [I]. Second;
If (d [V2]> d [v] + d) // notice that D [v]! = Inf & D! = Inf
{
If (d [V2]! = Inf)
{
Q. Erase (Q. Find (II (d [V2], V2 )));
}
D [V2] = d [v] + D;
Q. insert (II (d [V2], V2 ));
}
}
}
Return D;
}
Reference Source:
Topcoder Tutorials: power up C ++ with the standard template library: Part II: Advanced uses: Dijkstra by set
PS:
This is the most basic problem in graph theory. Today, we have finally finished it and regret the waste of time in the past .. Orz ..
This implementation is indeed very efficient. The result of submitting a question in Sicily:
Run ID user name problem language status run time run memory submit time
92839 rappizit 1387 C ++ accepted 0 sec 252 KB 2007-10-31 20:20:12
========================================================== ========================================================
2007-11-28 update:
Implemented via priority_queue, faster but use more memory, and add a statement: If (V = T) break; # include <vector>
# Include <queue>
# Include <functional>
Using namespace STD;
Typedef vector <int> VI;
Typedef pair <int, int> II;
Typedef vector <II> VII;
Typedef vector <VII> vvii;
Int Dijkstra (const vvii & G, int S, int T)
{
Const int INF = 0x7fffffff;
Int n = G. Size ();
Vi d (n, INF );
Priority_queue <II, vector <II>, greater <II> q;
D [s] = 0;
Q. Push (II (0, s ));
While (Q. Size ())
{
Ii p = Q. Top ();
Q. Pop ();
Int d = P. First, V = P. Second;
If (V = T) break;
If (d [v] <D) continue;
For (INT I = 0, j = G [v]. Size (); I <j; I ++)
{
Int v2 = G [v] [I]. First, D = G [v] [I]. Second;
If (d [V2]> d [v] + d) // d [v]! = Inf & D! = Inf
{
D [V2] = d [v] + D;
Q. Push (II (d [V2], V2 ));
}
}
}
Return (d [T] = inf? -1: d [T]);
}