The question tells you some distance (between two cities)
It is required that each city go through each time and finally return to the original location to find the shortest required distance.
Thought conversion:
The inbound and outbound degrees of each vertex are 1, which is equivalent to N cities on the left and N cities on the right. Optimal Matching is obtained by the nature of optimal matching, and each vertex is matched. It is equivalent to two occurrences of a vertex (not very good expression), that is, one inbound and one outbound. Therefore, the shortest distance is converted to the optimal matching problem.
View code
# Include < Stdio. h >
# Include < String . H >
# Include < Stdlib. h >
# Include < Algorithm >
Using Namespace STD;
# Define Min (a, B) a <B? A: B
# Define INF 999999
# Define Maxcompute 250
Int N, Match [Max];
Bool SX [Max], Sy [Max];
Int Lx [Max], Ly [Max], map [Max] [Max];
Bool PATH ( Int U)
{
SX [u] = True ;
For ( Int V = 0 ; V < N; V ++ )
If ( ! Sy [v] && Lx [u] + Ly [v] = Map [u] [v])
{
Sy [v] = True ;
If (Match [v] =- 1 | PATH (Match [v])
{
Match [v] = U;
Return True ;
}
}
Return False ;
}
Int Km ( Bool Truth) // You do not need to change the minimum or maximum weight match.
{
Int I, J;
If ( ! Truth)
{
For (I = 0 ; I < N; I ++ )
For (J = 0 ; J < N; j ++ )
Map [I] [J] =- Map [I] [J];
}
For (I = 0 ; I < N; I ++ )
{
Lx [I] =- INF;
Ly [I] = 0 ;
For (J = 0 ; J < N; j ++ )
If (LX [I] < Map [I] [J])
Lx [I] = Map [I] [J];
}
/* Memset (LX, 0, sizeof (LX); I don't know why this initialization is also an explanation //
// Memset (ly, 0, sizeof (ly )); */
Memset (match, - 1 , Sizeof (MATCH ));
For ( Int U = 0 ; U < N; u ++ )
While ( 1 )
{
Memset (sx, 0 , Sizeof (SX ));
Memset (SY, 0 , Sizeof (SY ));
If (Path (u )) Break ;
Int Dmin = INF;
For (I = 0 ; I < N; I ++ )
If (SX [I])
For (J = 0 ; J < N; j ++ )
If ( ! Sy [J])
Dmin = Min (LX [I] + Ly [J] - Map [I] [J], Dmin );
For (I = 0 ; I < N; I ++ )
{
If (SX [I])
Lx [I] -= Dmin;
If (SY [I])
Ly [I] + = Dmin;
}
}
Int Sum = 0 ;
For (J = 0 ; J < N; j ++ )
Sum + = Map [Match [J] [J];
If ( ! Truth)
{
Sum =- SUM;
For (I = 0 ; I < N; I ++ )
For (J = 0 ; J < N; j ++ )
Map [I] [J] =- Map [I] [J];
}
Return SUM;
}
Void Map_init ( Int M)
{
Int X, Y, W;
Int I, J;
For (I = 0 ; I < N; I ++ )
For (J = 0 ; J < N; j ++ )
Map [I] [J] = INF;
For (I = 0 ; I < M; I ++ )
{
Scanf ( " % D " , & X, & Y, & W );
If (Map [x - 1 ] [Y - 1 ] > W) // Please note that there may be duplicates.
Map [x - 1 ] [Y - 1 ] = W;
}
}
Int Main ()
{
Int T, M, X, Y, W, I;
Scanf ( " % D " , & T );
While (T -- )
{
Scanf ( " % D " , & N, & M );
Map_init (m );
Int Cost = Km ( False );
Printf ( " % D \ n " , Cost );
}
Return 0 ;
}
This question has caused many mistakes due to carelessness...
But the question is too BT, and the distance between the two cities will change .... Speechless .....