Avoid backtracking and backtracking
I didn't come to the blog Park for half a month. I changed my job and started to have a lot of complicated things. I had no time to write anything. This article was written elsewhere about half a year ago, but I think it is a good method, at least I personally think so. The backtracking method is uncontrollable. Sometimes unexpected results are generated beyond our expectation. The most common is memory leakage. I copied the original text, but I wrote it myself, and I didn't add any source. (If I reference others, I will add the source. I will not bury others' wisdom .)
The backtracking method is easy to think of and difficult to think of. Often, our thinking is easier to enter the Backtracking Method. But the backtracking method has its drawbacks. The obvious drawback is that the variables and references generated in the scope cannot be released when the backtracking method call is not completed (for most editors, exclude editors with optimization capabilities ). If we use a lot of backtracking calls in a method, the variables and references in the method scope cannot be promptly released in the method, in the end, the memory is insufficient and the computing load of the cpu increases. (In the memory mechanism, excess data can be transferred to the virtual memory or hard disk. This is not enough ). Using a stack (Team) loop can easily avoid backtracking, And the stack (Team) data can be easily thrown and removed after being used. In some cases, a small change can bring a program back to life in a specific environment. (I used a MongoDB algorithm before, and later improvements were made to avoid backtracking)
1 using System; 2 using System. collections. generic; 3 using System. linq; 4 using System. text; 5 using System. IO; 6 7 namespace avoid backtracking method 8 {9 class Program 10 {11 static void Main (string [] args) 12 {13 string path = AppDomain. currentDomain. baseDirectory; 14 15 List <string> fileList1 = new List <string> (); 16 FunctionHuishuo (path, ref fileList1 ); 17 18 List <string> fileList2 = new List <string> (); 19 FunctionQueue (path, ref fileList2); 20 21 List <string> fileList3 = new List <string> (); 22 FunctionStack (path, ref fileList3 ); 23} 24 25 /// <summary> 26 // Backtracking Method 27 /// </summary> 28 /// <param name = "path"> </param> 29 // <param name = "fileList"> </param> 30 private static void FunctionHuishuo (string path, ref List <string> fileList) 31 {32 if (true) 33 {34 string [] files = null; 35 try 36 {37 fil Es = Directory. GetFiles (path); 38} 39 catch {} 40 41 if (files! = Null & files. length> 0) 42 {43 fileList. addRange (files); 44} 45} 46 47 if (true) 48 {49 string [] folders = null; 50 try 51 {52 folders = Directory. getDirectories (path); 53} 54 catch {} 55 56 if (folders! = Null & folders. length> 0) 57 {58 foreach (string folder in folders) 59 {60 FunctionHuishuo (folder, ref fileList ); 61} 62} 63} 64} 65 66 // <summary> 67 // stack method 68 /// </summary> 69 // <param name = "path "> </param> 70 private static void FunctionStack (string path, ref List <string> fileList) 71 {72 Stack <string> stack = new Stack <string> (); 73 stack. push (path); 74 75 while (stack. count> 0) 76 {77 string dir = stack. pop (); 78 79 string [] files = null; 80 try 81 {82 files = Directory. getFiles (dir); 83} 84 catch {} 85 86 if (files! = Null & files. length> 0) 87 {88 fileList. addRange (files); 89} 90 91 string [] folders = null; 92 try 93 {94 folders = Directory. getDirectories (dir); 95} 96 catch {} 97 98 if (folders! = Null & folders. length> 0) 99 {100 foreach (string folder in folders) 101 {102 stack. push (folder ); 103} 104} 105} 106 107 108 // <summary> 109 // queue method 110 // </summary> 111 // <param name = "path "> </param> 112 private static void FunctionQueue (string path, ref List <string> fileList) 113 {114 Queue <string> queue = new Queue <string> (); 115 116 queue. enqueue (path); 117 118 while (queue. count> 0) 119 {120 String dir = queue. dequeue (); 121 122 string [] files = null; 123 try124 {125 files = Directory. getFiles (dir); 126} 127 catch {} 128 129 if (files! = Null & files. length> 0) 130 {131 fileList. addRange (files); 132} 133 134 string [] folders = null; 135 try136 {137 folders = Directory. getDirectories (dir); 138} 139 catch {} 140 141 if (folders! = Null & folders. length> 0) 142 {143 foreach (string folder in folders) 144 {145 queue. enqueue (folder); 146} 147} 148} 149} 150} 151}Code first
Please carefully compare the writing of the three types of loop structures. Pay special attention to the use of if (true ){...}, this method can produce amazing results in some editing environments. Do you want to create it?
Well, that's all. There's really no time to write new things. Post in the future should be slow, but there will be some posts on the server cluster. There are already many of these posts, but most of them are view text instructions, which is difficult for new users to grasp, I had a hard time exploring it myself. It requires a lot of servers, high-concurrency access, as well as core databases and differentiated database policies. If I use a post to explain it clearly, I feel like it is a fantasy, it can be written into a book, so it is the best way to explain the use of text in the cluster in a post. It is a comprehensive summary, so I did not blame the predecessors for writing the cluster knowledge too general, this is completely unknown. The predecessors wrote such brilliant posts for interested people. He wanted to teach us his ideas. I wrote all the posts for diaosi. Let's get started with knowledge, haha. (Master golang and erlang programming in advance)
Backtracking solves practical problems
Tc2.0 has been debugged to meet the question requirements.
# Include <stdio. h>
# Include <dos. h>
Int max = 0;/* Maximum number of values stored */
Int a [21], r [21];
/* A [] is used to store the placement combination generated each time. r [] is used to store the largest value of the storage combination */
Int vv [21];
Struct s
{Int w, v, I;
} X [21];/* structure for storing the value, label, and weight of an item */
Void solve (int n, int m, int * B, int * v, struct s * x );
Void save (void );
Int main ()
{Int n, m, I;
Printf ("M = ");
Scanf ("% d", & m );
Do
{Printf ("n = ");
Scanf ("% d", & n );
If (n <1 | n> 20) printf ("Data error. \ n ");
} While (n <1 | n> 20 );
For (I = 0; I <n; I ++)/* enter the information of each item */
{Printf ("w [% d] =", I + 1 );
Scanf ("% d", & (x [I]. w ));
Printf ("v [% d] =", I + 1 );
Scanf ("% d", & (x [I]. v ));
X [I]. I = I + 1;
}
System ("cls");/* clear screen */
For (I = 0; I <n; I ++)/* displays information about each item */
{Printf ("w [% d] = % d", I + 1, x [I]. w );
Printf ("v [% d] = % d \ n", I + 1, x [I]. v );
}
Printf ("m = % d \ n", m );
Solve (n, m, a, vv, x);/* Call function solving */
Printf ("ID of the saved item \ n ");
For (I = 0; r [I]> 0; I ++)
Printf ("% d", r [I]);
Printf ("\ n ");
Printf ("total value: % d \ n", max );
Getch ();
}
Void solve (int n, int m, int * B, int * v, struct s * x)
/* Functions solved using the Backtracking Method */
/* N indicates the remaining items, and m indicates the remaining space */
{Int I, w, f = 0;
/* F indicates whether the item can be put down in the remaining space. 1 indicates yes */
For (I = 0; I <n; I ++) if (m> = x [I]. w) f = 1;
If (! F) {B [0] =-1; save (); return ;}
If (n = 1)
{B [0] = x [0]. I; B [1] =-1; v [0] = x [0]. v; save (); return ;}
For (I = 0; I <n; I ++)
{If (m <x [I]. w) cont ...... remaining full text>
System Tracing
Previous algorithm tests
Barely look
The essence of backtracking is that you do not know the direction for solving the problem,
Just go straight forward with your scalp, and go wherever you can,
When there is no way to the end, you can go back to the previous intersection to test another road.
I personally feel a bit like in-depth graph traversal.
--------------------------------------------
// Eight queens
// 2008-04-23
// By leo
# Include <iostream>
Using namespace std;
# Define N 8 // Number of queens
Int x [N + 1] = {0}; // defines the chessboard
Bool place (int k) // determines whether the k position is properly placed by the Queen
{
Int I = 1;
While (I <k)
{
If (x [I] = x [k] | (abs (x [I]-x [k]) = abs (I-k) return false;
I ++;
}
Return true;
}
Void print () // print the result
{
For (int I = 1; I <N + 1; I ++)
Cout <x [I] <"";
Cout <endl;
}
Void nqueen (int k )//
{
Int count = 0; // NUMBER OF SOLUTIONS
While (k> = 1)
{
X [k] ++;
While (x [k] <= N &&! Place (k) // try the k queens from the first position
{
X [k] ++;
}
If (x [k] <= N) // The k Queen's security is in the checkerboard.
{
If (k = N) // if it is already the last Queen, a solution is available.
{
Count ++;
Cout <count <endl;
Print ();
}
Else k ++; // continue to process the next queen
}
Else x [k --] = 0; // If the k-th queen is not in the checker, backtrack
}
}
Void main ()
{
Nqueen (1 );
}... Remaining full text>