----- Classic backtracking
Problem: A salesman is going to sell goods in several cities. He knows the distance between cities (travel expenses). He wants to select one from the station and go through each city, finally, return to the station to minimize the total travel cost.
For example, the salesperson must go through 2, 3, and 4 from 1 and return 1.
It makes me feel like a problem of arrangement. During the calculation and arrangement, we must determine whether the arrangement is necessary, because we may be able to determine in the middle that this will definitely not get the expected results. At this time, we adopt backtracking. Code implementation:
1/* 2 * Salesperson Problem ---- backtracing 3 */4 # include <iostream> 5 using namespace STD; 6 7 # define Max 1024 8 9 int N = 4; // You can input it by yourself. Here I have specified it and set the cost [] []; 10 int cost [Max] [Max] for all vertices in Init (); // record the freight or price of any two points 11 int bestcost = max; // record the current minimum freight or price 12 INT currentcost; // The current freight or price 13 int current [Max]; // current path 14 int best [Max]; // record Optimal Path 15 16 void swap (Int & A, Int & B) 17 {18 int temp =; 19 A = B; 20 B = temp; 21} 22 23 void backtra CK (INT t) // is actually a problem of arrangement... 24 {25 Int J; 26 if (t = N) // to the last layer .. 27 {28 If (cost [current [T-1] [current [T] + cost [current [T] [1] + currentcost <bestcost) 29 {30 bestcost = cost [current [T-1] [current [T] + cost [current [T] [1] + currentcost; 31 for (j = 1; j <= N; j ++) 32 {33 best [J] = current [J]; 34} 35} 36} 37 38 for (j = T; j <= N; j ++) // arrange... 39 {40 swap (current [T], current [J]); 41 if (cost [current [T-1] [current [T] + currentcost <bestcost) // In fact currentcost is included in the 1 --> (t-1) price or freight 42 {43 currentcost + = cost [current [T-1] [current [T]; 44 backtrack (t + 1); // Recursive Backtracking 45 currentcost-= cost [current [T-1] [current [T]; 46} 47 swap (current [T], current [J]); 48} 49} 50 51 void Init () 52 {53 cost [1] [1] = 0; 54 cost [1] [2] = 30; 55 cost [1] [3] = 6; 56 cost [1] [4] = 4; 57 58 cost [2] [1] = 30; 59 cost [2] [2] = 0; 60 cost [2] [3] = 5; 61 cost [2] [4] = 10; 62 63 cost [3] [1] = 6; 64 cost [3] [2] = 5; 65 cost [3] [3] = 0; 66 cost [3] [4] = 20; 67 68 cost [4] [1] = 4; 69 cost [4] [2] = 10; 70 cost [4] [3] = 20; 71 cost [4] [4] = 0; 72} 73 void main () 74 {75 Init (); 76 77 int I; 78 for (I = 1; I <= N; I ++) 79 {80 current [I] = I; 81} 82 83 backtrack (2 ); // The first layer of the tree has been found, so 84 85 cout <"minimum freight:" <bestcost <Endl; 86 cout <"Optimal Path:"; 87 for (I = 1; I <= N; I ++) 88 {89 cout <best [I] <"->"; 90} 91 cout <best [1] <Endl; 92}
OK! O (∩) O Haha ~