Dynamic Planning

Objective: To understand the basic idea of dynamic planning and the overlapping nature of subproblems and the two basic elements of the dynamic planning algorithm. Master typical dynamic planning problems. Master the general methods for analyzing dynamic planning ideas, correctly analyze simple problems, design dynamic planning algorithms, and implement programming quickly.

Experiment content: Examples of programming implementation: Longest Common subsequence problem, matrix concatenation problem, convex polygon optimal triangle division problem, Circuit Wiring Problem, etc. In this experiment, we design algorithms and program them.

Exercise

1. Longest Common subsequence

The subsequence of a given sequence is obtained after several elements are deleted from the sequence. To be exact, if the given sequence X = <x1, x2 ,..., XM>, then another sequence z = <Z1, Z2 ,..., ZK> is the subsequence of X, which refers to the existence of a strictly incrementing subscript sequence <I1, I2 ,..., Ik>, so that for all j = 1, 2 ,..., K has

The answer is as follows:

A) Structure of the longest common subsequence

If the exhaustive search method is used, the time is too long and the algorithm requires exponential time.

The longest common subsequence of Yizheng is also of the optimal sub-structure.

Set sequence X = <x1, x2 ,..., XM> and Y = <Y1, Y2 ,..., One of the longest common subsequences of YN> Z = <Z1, Z2 ,..., ZK>, then:

I. If XM = YN, zk = XM = YN and the Zk-1 is the longest common subsequence of Xm-1 and Yn-1;

II. If XM =yn and ZK =xm, z is the longest common subsequence of Xm-1 and Y;

Iii. If XM =yn and ZK =yn, z is the longest common subsequence of x and Yn-1.

The Xm-1 = <x1, x2 ,..., Xm-1>, Yn-1 = <Y1, Y2 ,..., Yn-1>, Zk-1 = <Z1, Z2 ,..., Zk-1>.

The longest common subsequence problem has the optimal substructure.

B) recursive structure of subproblems

According to the optimal sub-structure nature of the longest common subsequence problem, we need to find x = <x1, x2 ,..., XM> and Y = <Y1, Y2 ,..., The longest common subsequence of YN> can be recursively performed in the following way: When XM = YN, find the longest common subsequence of Xm-1 and Yn-1, add xm (= yn) to the end of the sequence to obtain the longest common subsequence of X and Y. When XM =yn, two subproblems must be solved: finding one of the longest common subsequences of Xm-1 and Y and one of the longest common subsequences of x and Yn-1. The elders of the two common subsequences are the longest common subsequences of X and Y.

From this recursive structure, it is easy to see that the longest common subsequence problem has subproblem overlapping nature. For example, when calculating the longest common subsequences of X and Y, the longest common subsequences of x and Yn-1 and Xm-1 and Y may be calculated. Both of these subproblems contain a common subproblem, that is, the longest common subsequence for calculating Xm-1 and Yn-1.

Let's establish a recursive relationship between the Optimal Values of sub-problems. Use C [I, j] to record the length of the longest common subsequence of sequence XI and YJ. Xi = <x1, x2 ,..., Xi>, YJ = <Y1, Y2 ,..., YJ>. When I = 0 or J = 0, the null sequence is the longest common subsequence of Xi and YJ, So C [I, j] = 0. Build a recursive relationship as follows:

C) Calculate the optimal value

In the subproblem space, there are only θ (M * n) Different subproblems. Therefore, using the dynamic planning algorithm to calculate the optimal value from the bottom up can improve the efficiency of the algorithm.

The Dynamic Programming Algorithm lcs_length (x, y) used to calculate the longest common sub-sequence length ,..., XM> and Y = <Y1, Y2 ,..., YN> as input. Output two arrays C [0 .. m, 0 .. n] and B [1 .. m, 1 .. n]. C [I, j] stores the length of the longest common subsequence of Xi and YJ, and B [I, j] records indicate C [I, j] The value is obtained by the subproblem, which is used to construct the longest common subsequence. Finally, the length of the longest common subsequences of X and Y is recorded in C [M, N.

The procedure is as follows:

# Include <stdio. h>

# Include <string. h>

Int lcs_length (char X [], char y []);

Int main ()

{

Char X [2, 100], Y [2, 100];

Int Len;

While (1)

{

Scanf ("% S % s", x, y );

If (X [0] = '0') // convention that the first string ends with '0'

Break;

Len = lcs_length (x, y );

Printf ("% d/N", Len );

}

}

Int lcs_length (char X [], char y [])

{

Int m, n, I, j, L [100] [100];

M = strlen (X );

N = strlen (y );

For (I = 0; I <m + 1; I ++)

L [I] [0] = 0;

For (j = 0; j <n + 1; j ++)

L [0] [J] = 0;

For (I = 1; I <= m; I ++)

For (j = 1; j <= N; j ++)

If (X [I-1] = Y [J-1]) // I, j starts from 1, but the string is from 0

L [I] [J] = L [I-1] [J-1] + 1;

Else if (L [I] [J-1]> L [I-1] [J])

L [I] [J] = L [I] [J-1];

Else

L [I] [J] = L [I-1] [J];

Return L [m] [N];

}

Because the calculation of each array unit consumes partial (1) time, the lcs_length algorithm consumes partial (Mn) time ).

Thinking: Can space be saved?

2. Calculate the Matrix Product

In scientific computing, we often need to calculate the product of a matrix. The conditions that matrix A and B can be multiplied are that the number of columns in matrix A is equal to the number of rows in matrix B. If a is a matrix of P x q and B is a matrix of q x r, the product C = AB is a matrix of P X R. According to this formula, the total number of pqr requests required for C = AB is calculated. The standard formula is as follows:

The problem is that N matrices {A1, A2,… are given ,..., An }. Among them, AI and AI + 1 are multiplication, I = 1, 2 ,..., N-1. Calculate the product a1a2 of the N matrices... An.

Recursive Formula:

The procedure is as follows:

# Include <stdio. h>

Int main ()

{

Int P [101], I, J, K, R, t, n;

Int M [101] [101]; // The array starts from 1 in order to be consistent with the explanation.

Int s [101] [101]; // records the disconnection position from nth I to nth J matrix concatenation

Scanf ("% d", & N );

For (I = 0; I <= N; I ++)

Scanf ("% d", & P [I]); // read the value of P [I] (Note: P [0] to P [N] n + 1 in total)

For (I = 1; I <= N; I ++) // initialize M [I] [I] = 0

M [I] [I] = 0;

For (r = 1; r <n; r ++) // R is the difference between I and j.

For (I = 1; I <n; I ++) // I is a row

{

J = I + R; // J is the column

M [I] [J] = m [I + 1] [J] + P [I-1] * P [I] * P [J]; // assign an initial value to M [I] [J]

S [I] [J] = I;

For (k = I + 1; k <j; k ++)

{

T = m [I] [k] + M [k + 1] [J] + P [I-1] * P [k] * P [J];

If (T <m [I] [J])

{

M [I] [J] = T; // M [I] [J] obtains the minimum value.

S [I] [J] = K;

}

}

}

Printf ("% d", M [1] [N]);

}

3. Optimal triangle partitioning of Convex Polygon

A polygon is a linear closed curve on a piecewise plane. That is to say, a polygon is composed of a series of straight lines connected at the beginning and end. The straight lines that make up a polygon are called the edges of the polygon. The point at which a polygon connects to two edges is called the vertex of a polygon. If there is no common point between the edges of a polygon except the vertex, the polygon is called a simple polygon. A simple polygon divides the plane into three parts: All Points enclosed in the polygon form the interior of the polygon, And the polygon itself form the boundary of the polyon; the remaining points on the plane form the exterior of the polygon. When a simple polygon and its interior form a closed convex set, the polygon is called a convex polygon. That is to say, all vertices in the linear segment connected to any two points on the convex polygon boundary or any other two points inside the convex polygon are on the interior or boundary of the polygon.

Generally, a convex polygon is expressed using the clockwise sequence of the polygon vertices, that is, P = <v0, V1 ,... , Vn-1> indicates that there are n sides v0v1, v1v2 ,... , A convex polygon of the vn-1vn, where, agreed V0 = Vn.

If VI and vj are two vertices not adjacent to a polygon, the line segment vivj is called a chord of a polygon. The string splits the Polygon into two convex sub-polygon <VI, vi + 1 ,... , VJ> and <VJ, vj + 1 ,... , VI>. The triangle division of a polygon is a set t that splits a Polygon into a string of a triangle that does not overlap with each other. It is two different triangles of a convex polygon.

The problem with the optimal triangle division of a convex polygon is: Given a convex polygon P = <v0, V1 ,... , Vn-1> and Weight Function ω defined on a triangle consisting of edges and chords of a polygon. Determine a triangle of the convex polygon so that the corresponding weight of the triangle is the sum of the weights on the triangles in the triangle.

Various weights W can be defined on a triangle. For example, you can define ω (△vivjvk) = | vivj | + | vivk | + | vkvj |, where, | vivj | indicates the Euclidean distance between a vertex VI and a VJ. Corresponding to this weight function, the optimal triangle is the smallest string Yangtze river delta. (Note: The algorithm used to solve this problem must apply to any weight function)

4. defensive missiles

A new defensive missile can intercept multiple attack missiles. It can fly forward or fly down quickly. It can intercept attacking missiles without any damage, but it cannot fly backward or upwards. However, there is a drawback that, although it can reach any height at the time of launching, it can only intercept missiles with the same height or height as the previous missile interception. This new defensive missile is now being tested. In each test, a series of tested missiles are launched (these missiles are launched at fixed intervals with the same flight speed ), the information that the defensive missile can obtain includes the height of each attacking missile and their launch sequence. A program is required to calculate the maximum number of attacking missiles that can be intercepted by the defensive missile during each test. One missile can be intercepted and must meet one of the following two conditions:

A) It is the first missile to be intercepted by a defensive missile in this test;

B) It is a missile launched after the last missile was intercepted, and its height is not higher than that of the last missile.

Input data: the first line is an integer N, And the next n each has an integer representing the height of the missile.

Output Data: Maximum number of intercepted missiles.

Analysis: defines L [I] as the number of missiles that can be intercepted at most from the moment of selection of the I missile.

Because I missile is selected, the height of the next missile J to be intercepted must be smaller than or equal to its height. Therefore, L [I] should be equal to every J from I + 1 to n, satisfies the maximum value of L [J] In J of H [J] <= H [I.

The procedure is as follows:

# Include <stdio. h>

Int main ()

{

Int I, j, N, Max, H [100], L [100];

Scanf ("% d", & N );

For (I = 0; I <n; I ++)

Scanf ("% d", & H [I]);

[N-1] = 1;

For (I = n-2; I> = 0; I --)

{

Max = 0;

For (j = I + 1; j <n; j ++)

If (H [I]> H [J] & max <L [J])

Max = L [J];

L [I] = MAX + 1;

}

Printf ("% d", l [0]);

}

5. Merge stones

There are n piles of stones (n <= 100) placed around a circular playground. Now we need to combine the stones into a pile in order. It is specified that only two adjacent heaps can be selected to be merged into a new heap, and the number of stones in the new heap is recorded as the score of the merge. Compile a program. The number of stacks N is read from the file and the number of stones per stack (<= 20 ).

Select a method for merging stones to minimize the total score for n-1 merge operations;

Input data:

The first behavior is the number of stone heaps N;

The second act is the number of stones in each heap, separated by a space.

Output Data:

The merge plan with the smallest score from the first to the nth behavior. Row n + 1 is a blank row. From row n + 2 to row 2n + 1 is the largest merge of scores. Each merge scheme is represented by N rows, where line I (1 <= I <= N) represents the number of stones in each heap before the I merge (output in clockwise order, which heap can be output first ). The number of stones to be merged must be negative.

Sample Input

4

4 5 9 4

Sample output

-4 5 9-4

-8-5 9

-13-9

22 4-5-9 4

4-14-4

-4-18

22

6. Minimum Cost subtree

There are n numbers in a row, for example, 22 14 7 13 26 15 11. Any two adjacent numbers can be merged. The Merging cost is the sum of the two numbers. After continuous merging, the merge cost is regarded as a pile, and the sum of the total merging costs is called the total cost, A merge algorithm is provided to minimize the total cost.

The format of input and output data is the same as that of "Stone merge.

Sample Input

4

12 5 16 4

Sample output

-12-5 16 4

17-16-4

-17-20

37

7. Store Shopping

Each item in a store has a price. For example, the price of a flower is 2 ICU (ICU is the unit of currency for the informatics competition); the price of a vase is 5 ICU. To attract more customers, the store offers special preferential prices. A special discount product is a group of one or more products. And price reduction. For example, the price of 3 flowers is not 6 but 5 ICU; 2 vase and 1 flower are 10 ICU, not 12 ICU.

Compile a program to calculate the cost of the product purchased by a customer. Make full use of the preferential price to minimize the customer's payment. Please note that you cannot change the type and quantity of the products purchased by the customer. You are not allowed to make any changes even if you increase the number of products to reduce the total payment amount. Assume that the prices of various products are as described above, and a customer buys three flowers and two vases. The customer's payable is 14 ICU because:

1 flower plus 2 vase discount price: 10 ICU

Normal price of 2 flowers: 4 ICU

Input data: the first file input. txt describes the items purchased by the customer (placed in the shopping basket); the second file describes the preferential products and prices provided by the store (the file name is off er. txt ). Both files only use integers.

The format of input. txt In the first file is: the first line is a number B (0 ≤ B ≤ 5), indicating the number of purchased product types. There are a total of B rows below. Each row contains 3 numbers C, K, and P. C Indicates the product code (each product has a unique code), 1 ≤ C ≤ 999. K represents the total number of purchases for this product, 1 ≤ k ≤ 5. P is the normal unit price of the product (the price of each product), 1 ≤ p ≤ 999. Please note that up to 5*5 = 25 items can be placed in the shopping basket.

The format of the second offer. txt file is: the first line is a number S (0 ≤ S ≤ 9 9), indicating a total of S discounts. The following is a total of S lines. Each line describes the types of products in a combination of discount products. Below are several numeric pairs (C, k), where C represents the commodity code, 1 ≤ C ≤ 9 99. K represents the quantity of the product in this combination, 1 ≤ k ≤ 5. The last digit P (1 ≤ p ≤ 9999) of the Bank represents the preferential price of the product portfolio. Of course, the discount price is lower than the total normal price of the product in the combination.

Output data: in the output file output. txt, write a number that occupies one row. This number indicates the minimum payment for the purchased product (the input file indicates the purchased product.

8. travel budget

A travel agency needs to estimate the minimum cost of taking a car from a city to another city. There are several gas stations along the road, and the charges for each gas station are not necessarily the same. The travel budget has the following rules:

If the fuel tank is over half the fuel, no fuel is stopped, unless the fuel in the fuel tank cannot be supported until the next stop. The fuel is full every time it is refueled. During a gas station, the driver needs to spend 2 yuan to buy something to eat; the driver does not have to prepare additional oil for other unexpected situations. When the car leaves, it fills the fuel tank at the starting point. The calculation is accurate to the minute (1 yuan = 100 points ). Write a program to estimate the minimum cost of actually traveling on a certain route.

Input data: read data from the text file "route. dat" in the current directory. Enter several travel routes in the following format:

Distance from the start point to the end point of the first behavior (real number)

The second act is three real numbers, followed by an integer, separated by a space. Among them, the first number is the capacity of the car tank (litre), the second number is the Kilometer number of each litre of gasoline driving, the third number is the cost of filling the tank at the starting point, and the fourth number is the number of gas stations. (<= 50 ). The next row contains two real numbers. Each data is separated by a space. The first number is the distance from the gas station to the start point, the second number is the price of the gas station per litre of gasoline (Yuan/litre ). Gas stations are listed in ascending order of their distance from the starting point. All inputs have a certain solution.

Output data: the answer is output to the text file "route. Out" in the current directory. The file contains two rows. The first act is a real number and an integer. The real number is the minimum travel fee, in Yuan, accurate to the minute. The integer indicates the N of the station on the way. The second row is an integer of N, indicating the numbers of the stations for N refuel. The numbers are listed in ascending order. Data is separated by a space, and there is no extra space.

Sample Input

516.3 38.09 1

15.7 22.1 20.87 3 2

125.4 1.259

297.9 1.129

345.2 0.999

Sample output

38.09 1

2

9. Palace Guard

After the Taiping Wang shizi incident, Lu Xiaofeng became the royal master's first product guard specially hired by the emperor. The palace starts with a midday entrance, and is in the shape of a tree in the lower Palace of the princess; some palaces can see each other. Inside the palace, security is strict, with three steps and one guard, and every palace must be guarded around the clock. The cost of arranging detention centers in different palaces is different. However, Lu Xiaofeng has insufficient funds, and in any case he cannot place a left-behind guard in every palace.

Please use programming computing to help Lu Xiaofeng arrange the guards and minimize the cost while guarding all the palaces.

Input data: the input data is provided by a text file named intput.txt. The data in the input file indicates a tree. The description is as follows:

Line n of row 1st indicates the number of nodes in the tree.

Line 2nd to line n + 1, each line describes the information of each palace node, in turn: The Palace node number I (0 <I <= N ), k. The number of sons on the edge is m, and the number of M sons on the edge is R1, R2 ,..., rm.

For a tree with N (0 <n <= 1500) nodes, the node number is between 1 and N, and the number is not repeated.

Output Data: output to the output.txt file. The output file contains only one number, which is the minimum cost.

Example of input data in the right image:

Sample Input

6

1 30 3 2 3 4

2 16 2 5 6

3 5 0

4 4 0

5 11 0

6 5 0

Sample output

25

10. Game room problems

There is a game room with multiple game rooms, and each game room has multiple game rooms, each with a game room, and so on. You can get a certain amount of happiness when you enter each game room. The ticket price for each game room is greater than or equal to 0, and there is a happy value. Only when you enter a game room can you enter its internal game room, james now has N yuan to ask how much happiness he can get.

11. * genetic problems

We know two gene sequences: S: agtagt; T: attag. Now you need to add spaces to the sequence so that the length of the two sequences is equal, and the value of the matching symbol of the two strings is the maximum. There are only four types of genes, which are represented by A, G, C, and T. Two spaces are not allowed to match each other. The matching values of any two symbols are given in the following table:

A g c t 〕

A 5-2-1-2-4

G-2 5-4-3-2

C-1-4 5-5-1

T-2-3-5 5-2

]-4-2-1-2

Tip: defining question l [I] [J] is to take the first I item of the first sequence and the first J item of the second sequence. The two sequences have the maximum value of space matching. The optimal value is related to three subquestions: L [I-1] [J-1], L [I] [J-1], L [I-1] [J].

The recursive formula is as follows:

M [0] [t [J] indicates the matching values of the table's hollow and T [J.

Thinking: initialization of this issue.

12. * Tianji horse racing

Tian Ji and Qi Wang both have n horses (n <= 100), and each bet is one or two gold horses. Now we know the speed of each horse between Qi Wang and Tian Ji, in addition, Qi Wang must be playing fast and slowly by horse. Now you need to write a program to help Tian Ji calculate how much gold he will win in the best result (which is expressed by a negative number ).

Analysis: sort the data first. The speed of Qi Wang's horse is placed in array A, and the speed of Tian Ji's horse is placed in array B. The algorithms used in this issue are a combination of Dynamic Planning and greedy algorithms. Start with the weakest horse:

If Tian Ji's horse is fast, let the two horses compete;

If Tian Ji's horse was slow, he simply asked him to deal with Qi Wang's fastest horse;

If the two horses are at the same speed, there are two options, either match them or match the fastest horse from Qi Wang.

Define sub-problem: L (I, j) is Qi Wang's fastest J-horse competition between J-horse and Tian Ji starting from I-horse, and Tian Ji's biggest benefit.

Then:

When the program is implemented, in order to adapt to a slight change of C data starting from 0, the sub-problem is defined: L (I, j) qi Wang's fastest J + 1 horse race between I horse and Tian Ji from I horse to I + J horse, tian Ji's biggest gains. At initialization: L [I] [0] indicates the result of Qi Wang's fastest match between I horse and Tian Ji.

The procedure is as follows:

# Include <stdio. h>

Void readdata ();

Void Init ();

Int n, a [100], B [100], L [100] [100];

Int main ()

{

Int I, J;

Readdata ();

Init ();

For (I = n-2; I> = 0; I --)

For (j = 1; j <n-I; j ++)

If (A [I + J] <B [J])

L [I] [J] = L [I] [J-1] + 1;

Else if (a [I + J]> B [J])

L [I] [J] = L [I + 1] [J-1]-1;

Else if (L [I + 1] [J-1]-1> L [I] [J-1])

L [I] [J] = L [I + 1] [J-1]-1;

Else

L [I] [J] = L [I] [J-1];

Printf ("% d", l [0] [n-1]);

}

Void readdata ()

{

Int I;

Scanf ("% d", & N );

For (I = 0; I <n; I ++)

Scanf ("% d", & A [I]);

For (I = 0; I <n; I ++)

Scanf ("% d", & B [I]);

}

Void Init ()

{

Int I;

// Qsort (A, n); // omitted

For (I = 0; I <n; I ++)

{

If (A [I] <B [0])

L [I] [0] = 1;

Else if (a [I] = B [0])

L [I] [0] = 0;

Else

L [I] [0] =-1;

}

}