Bare shortest, try to just see the SPFA, although not look at the code, but understand the general idea, first write a try it, and is a sparse map, it should be soon.
Spfa
The algorithm adopts graph storage structure as adjacency table, and the method is dynamic optimization approximation method. The algorithm sets up an advanced firstout of the queueQueueused to save vertices to be optimized, and to extract a point from this queue in order of optimizationW, and withWthe current path of the pointD[w]to optimize the path values of other pointsD[j], if there is an adjustment, thatD[j]the value is changed to a smallerwill beJPoint intoQueuequeue to continue further optimization. repeatedly fromQueuetake out points in the queue to the current shortestuntil team space does not need to be optimized,DThe shortest path from the source point to each point is saved in the array.diameter value
///////////////////////////////////////////////////////////////////////////
Once again ... It's a wonderful feeling, it's a lot easier to write.
#include <algorithm>
#include <queue>
#include <stdio.h>
#include <string.h>
#include <vector>
usingnamespaceStd
ConstintMAXN =1005;
ConstintOO =0xFFFFFFF;
structNode
{
intY, Len;
NodeintYintLen): Y (y), Len (len) {}
};
Vector<node> G[MAXN];
intV[MAXN];
voidSPFA (intS
{
queue<int> Q;
Q.push (s);
while(Q.size ())
{
s = Q.front (); Q.pop ();
intLen = G[s].size ();
for(intI=0; i<len; i++)
{
Node q = g[s][i];
if(V[s]+q.len < V[Q.Y])
{
V[Q.Y] = V[s]+q.len;
Q.push (Q.Y);
}
}
}
}
intMain ()
{
intT, N;
while(SCANF ("%d%d", &t, &n)! = EOF)
{
intI, A, B, Len;
for(i=0; i<t; i++)
{
scanf"%d%d%d", &a, &b, &len);
G[a].push_back (node (b, Len));
G[b].push_back (Node (a, Len));
}
for(i=1; i<=n; i++)
V[i] = oo;
v[1] =0;
SPFA (1);
printf"%d\n", V[n]);
for(i=1; i<=n; i++)
G[i].clear ();
}
return0;
}
A-til the Cows Come Home