Layout
This topic is still written in over 400 ms using the spfa + stack. I found that all modules can be applied. Except for the input, the other modules are basically the same.
Module 1: initializes arrays.
Module 2: edge adding and edge joining table Processing
Module 3: The spfa stack implementation process
Code
# Include < Stdio. h >
# Include < Stdlib. h >
# Define INF 0 xfffffff
# Define Nn 1004
# Define MM 20004
Int Ednum, N;
Int Next [mm];
Int Root [NN];
Int Mark [NN];
Int CNT [NN];
Int Dis [NN];
Int Stack [NN];
Struct Node {
Int E, V;
} Edge [mm];
/* Here I use a function to complete initialization, or I can look at a fixed module. */
/* Module 1 */
Void Init (){
Int I;
For (I = 0 ; I <= N; I ++ ){
Root [I] = - 1 ;
Mark [I] = 0 ;
CNT [I] = 0 ;
}
}
/* Module 2 */
Void Add ( Int A, Int B, Int C ){
Edge [ednum]. e = B;
Edge [ednum]. v = C;
Next [ednum] = Root [a];
Root [A] = Ednum ++ ;
}
/* The function returns-1, indicating that there is a negative edge weight loop, which indicates that it is impossible.
If the function returns-2, it indicates that the distance from the start point to the end point is uncertain. Here, we use dis [N] = inf to judge, because the start value is INF.
Otherwise, DIS [N] is returned, where the maximum distance from the start point to the end point is stored.
*/
/* Module 3 */
Int Spfa ()
{
Int I, top, cur, TMP, NXT;
Top = 0 ;
For (I = 1 ; I <= N; I ++ ){
Dis [I] = INF;
If (Root [I] ! = - 1 ){
Stack [ ++ Top] = I;
CNT [I] ++ ;
Mark [I] = 1 ;
}
}
Dis [ 1 ] = 0 ;
While (Top ){
Cur = Stack [Top -- ];
TMP = Root [cur];
Mark [cur] = 0 ;
While (TMP ! = - 1 ){
NXT = Edge [TMP]. E;
If (DIS [NXT] > Dis [cur] + Edge [TMP]. v ){
Dis [NXT] = Dis [cur] + Edge [TMP]. V;
If ( ! Mark [NXT]) {
CNT [NXT] ++ ;
If (CNT [NXT] > N + 1 ){
Return - 1 ;
}
Mark [NXT] = 1 ;
Stack [ ++ Top] = NXT;
}
}
TMP = Next [TMP];
}
}
If (DIS [N] = INF ){
Return - 2 ;
}
Return Dis [N];
}
Int Main ()
{
Int ML, MD, A, B, C;
Scanf ( " % D " , & N, & ML, & MD );
Init ();
While (Ml -- ){
Scanf ( " % D " , & A, & B, & C );
Add (A, B, C );
}
While (MD -- ){
Scanf ( " % D " , & A, & B, & C );
Add (B,, - C );
}
Printf ( " % D \ n " , Spfa ());
// System ("pause ");
Return 0 ;
}