Shortest Path ....
Because the number of points is more than 1000, if the dijstra algorithm o (n ^ 2) definitely times out, the spfa algorithm is used here.
The memory is slightly larger because no adjacent table is used.
The algorithm is very simple. We still need to build a forward graph, reverse graph, and find the shortest distance from the starting point to other points respectively, then sum, that is, starting from this point, then return the shortest distance, and finally obtain the maximum value.
Code:
[Cpp]
# Include <stdio. h>
# Define maxn1001
# Define inf 100000000
Int n, x, m;
Int mat [maxN] [maxN]; // forward graph adjacent matrix
Bool flag [maxN] [maxN]; // forward graph flag Matrix
Int re_mat [maxN] [maxN]; // inverse graph adjacent matrix
Bool re_flag [maxN] [maxN]; // reverse icon Matrix
Int dis [maxN]; // the shortest path from the start point to another Vertex
Int disRes [maxN]; // round-trip Shortest Path and
Bool vis [maxN]; // indicates the point in the queue
Int queue [10 * maxN]; // spfa queue
// Initialize the adjacent matrix
Void Init ()
{
For (int I = 1; I <= n; ++ I)
{
For (int j = 1; j <= n; ++ j)
{
Mat [I] [j] = inf;
Flag [I] [j] = false;
Re_mat [I] [j] = inf;
Re_flag [I] [j] = false;
}
DisRes [I] = 0;
}
}
// Spfa Algorithm
Void spfa (int mat [] [maxN], bool flag [] [maxN])
{
For (int I = 1; I <= n; ++ I)
{
Vis [I] = false;
Dis [I] = inf;
// DisRes [I] = 0;
}
Int head = 0, tail = 1;
Dis [x] = 0;
Queue [0] = x;
While (head <tail)
{
Int u = queue [head];
Vis [u] = true;
For (int I = 1; I <= n; ++ I)
{
If (flag [u] [I] & dis [I]> dis [u] + mat [u] [I])
{
Dis [I] = dis [u] + mat [u] [I];
If (! Vis [I])
{
Vis [I] = true;
Queue [tail] = I;
Tail ++;
}
}
}
Vis [u] = false;
Head ++;
}
For (int I = 1; I <= n; ++ I)
{
DisRes [I] + = dis [I];
}
} Www.2cto.com
Int main ()
{
While (scanf ("% d", & n, & m, & x )! = EOF)
{Int a, B, c;
Int mMax =-1;
Init ();
For (int I = 0; I <m; ++ I)
{
Scanf ("% d", & a, & B, & c );
Mat [a] [B] = c;
Flag [a] [B] = true;
Re_mat [B] [a] = c;
Re_flag [B] [a] = true;
}
Spfa (mat, flag );
Spfa (re_mat, re_flag );
For (int I = 1; I <= n; ++ I)
{
If (mMax <disRes [I])
{
MMax = disRes [I];
}
}
Printf ("% d \ n", mMax );
}
Return 0;
}
Author; zhang20072844