Algorithms Chapter Summary

First, the concept of backtracking algorithms and understanding

  Concept: backtracking (exploration and backtracking) is an optimal selection search method, also known as heuristics, search forward Press to excellent condition, in order to achieve our goals.

  Appreciated: In backtracking, the expansion of the current partial solution each time, are facing an optional set of states, a new partial solutions by selecting it in the set is constructed. Such a set of states, which is more than one tree structures, each tree node represents a possible partial solution, it is the son of the other partial solution on the basis of its generation. Root initial state, this state is called the state space set tree.

 

Second, the solution space structure "subset and the" constraint function issues and

  1, the structure of the solution space

  The set of non-negative integers different from zero S = {x1, x2, ..., xn} of elements corresponding to a subset S1, S1 and is in c.

    2, constraint functions

   if (sum + temp[t] <= c) 

   sum is the sum of that value is not currently traversed to the plus, temp array is traversed, c is required for the optimal solution (and is the greatest).

    If the number is greater than, that node is discarded

   3. Source Code

   

 1 #include <iostream>
 2 using namespace std;
 3 int n, c, d = 0, f = 0, k = 0;
 4 int a[10000], b[10000], e[10000],add[10000];
 5 
 6 void backtrack(int i)
 7 {
 8 if (i > n || f == 1) return;
 9 d += a[i];
10 b[i] = 1;
11 if (d != c)
12 {
13 if (d < c && (c - d < add[i])) backtrack(i + 1);
14 d -= a[i];
15 b[i] = 0;
16 backtrack(i + 1);
17 }
18 else
19 {
20 f = 1;
21 for (int j = 1; j <= i; j++)
22 if (b[j] == 1 && a[j] != 0) e[k++] = a[j];
23 }
24 }
25 
26 int main()
27 {
28 cin >> n >> c;
29 for (int i = 1; i <= n; i++)
30 cin >> a[i];
31 for (int j = n - 1; j >= 0; j--)
32 add[j] = add[j + 1] + a[j];
33 backtrack(1);
34 if (f == 0) cout << "No Solution!";
35 else
36 {
37 for (int i = 0; i < k; i++)
38 {
39 cout << e[i] << ' ';
40 }
41 }
42 system("pause");
43 return 0;
44 }

 

Third, the problems encountered in this chapter and bear case for programming

1, problems encountered

Probably Shangjishijian time, facing the first 0-1 knapsack problem has been Sike, because then have to think how to better constraint functions, the card has been timed out, leading to a question did not break out. I felt it very hard to accept!

2, the case where pair programming

They exchange a semester of programming ideas, we learned a lot, after all, different people different thinking. Then also cooperate with each other large operations, division of labor was written.

Guess you like

Origin www.cnblogs.com/zz010/p/12070895.html