Given a directed graph and a starting point of N + 1 points, find the shortest path that passes through the remaining N points and return to the starting point .. (N <= 10)
Analysis: when we see such a small amount of data, we will know that it is not a common short circuit. First of all, if n is so small, we should think of State compression, each bit indicates which vertex has passed...
DP [I] [J] indicates the shortest path length when the arrival point I state is J. A bit is ignored at the beginning, that is, the updated vertex, which is likely to be updated again, therefore, we cannot simply record whether the status has been updated, so we thought of using spfa to team up updated points and continue to expand ......
View code
# Include <iostream> # Include <Algorithm> # Include <Queue> Using Namespace STD; Const Int N = ( 1 <11 ) + 10 ; Int Map [ 15 ] [ 15 ], N; Int DP [ 15 ] [N]; Bool Vis [ 15 ] [N]; Struct Node { Int V, State; node () {} node ( Int V, Int State): V (V), State (State ){}}; Void Spfa () {memset (VIS, False , Sizeof (VIS); memset (DP, - 1 , Sizeof (DP); DP [ 0 ] [ 0 ] =0 ; Queue <Node> Q; q. Push (node ( 0 , 0 ); Vis [ 0 ] [ 0 ] = True ; While (! Q. Empty () {node TMP = Q. Front (); q. Pop (); vis [TMP. V] [TMP. State] = False ; For ( Int I = 0 ; I <n; ++ I ){ If (TMP. V = I) Continue ; If (DP [I] [TMP. state | ( 1 <I)] =- 1 | DP [I] [TMP. state | ( 1 <I)]> DP [TMP. V] [TMP. State] +Map [TMP. V] [I]) {DP [I] [TMP. State | ( 1 <I)] = DP [TMP. V] [TMP. State] + Map [TMP. V] [I]; If (! Vis [I] [TMP. state | ( 1 < I)]) {vis [I] [TMP. State | ( 1 <I)] = True ; Q. Push (node (I, TMP. State | ( 1 <I )));}}}}} Int Main (){ While (Scanf ( " % D " , & N) = 1 && N) {n ++ ; For ( Int I = 0 ; I <n; ++ I) For ( Int J = 0 ; J <n; ++ J) scanf ( " % D " ,& Map [I] [J]); spfa (); printf ( " % D \ n " , DP [ 0 ] [( 1 <N )- 1 ]);} Return 0 ;}