Pku3311 hie with the pie (spfa + state compression)

Source: Internet
Author: User

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  ;} 

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.