最短路常用的三种算法
int Dijkstra( int Start, int End, int N )
{
memset( Length, 0x7f, sizeof( Length ) );
memset( Visited, false, sizeof(Visited) );
Length[Start] = 0;
Visited[Start] = true;
int Now = Start;
for( int i = 0; i < N; i++ )
{
for( int j = 1; j <= N; j++ )
{
if( Mat[j][Now] + Length[Now] < Length[j] && !Visited[j] )
Length[j] = Mat[j][Now] + Length[Now];
}
for( int j = 1; j <= N; j++ )
if( !Visited[j] )
{
Now = j;
break;
}
for( int j = 1; j <= N; j++ )
{
if( Length[j] < Length[Now] && !Visited[j] )
Now = j;
}
Visited[Now] = true;
}
return Length[End];
}
int SPFA( int Start, int End, int N )
{
queue<int> Q;
memset( Visited, false, sizeof(Visited) );
memset( Dist, 0x3f, sizeof( Dist ) );
while( !Q.empty() )
Q.pop();
Dist[Start] = 0;
Visited[Start] = true;
Q.push( Start );
while( !Q.empty() )
{
int Now = Q.front();
Q.pop();
Visited[Now] = false;
for( int i = 1; i <= N; i++ )
{
if( Dist[Now] + Mat[Now][i] < Dist[i] )
{
Dist[i] = Dist[Now] + Mat[Now][i];
if( !Visited[i] )
{
Visited[i] = true;
Q.push( i );
}
}
}
}
return Dist[End];
}
void Floyd( int Now, int N )
{
for( int i = 0; i < N; i++ )
for( int j = 0; j < N; j++ )
if( Mat[i][j] > Mat[i][Now] + Mat[Now][j] )
Mat[i][j] = Mat[i][Now] + Mat[Now][j];
}