Bar Code problem dp + Method for Finding the serial number of a sequence in a certain arrangement, bar code dp

Source: Internet
Author: User

Bar Code problem dp + Method for Finding the serial number of a sequence in a certain arrangement, bar code dp

Question

A Bar code is a symbol that appears alternately between a Light Bar and a Dark Bar and starts with a Dark Bar. Each Bar occupies several units of width. Figure 33-1 shows a bar code containing four lines, extending the width of 1 + 2 + 3 + 1 = 7 units.

In general, BC (N, K, M) is a program that contains all K records. The total width is equal to N Units, the width of each bar is a collection of bar codes in MB. For example, the barcode in Figure 33-1 belongs to BC (, 3) but not BC (, 2 ). Figure 33-2 shows all 16 symbols in the Set BC (, 3), where 1 indicates dark and 0 indicates bright. The bar code shown in the figure is alphabetically arranged, and the number on the left of the colon is the number of the bar code. Figure 33-1 bar code in BC (, 3) is numbered 4.

Input Format:

Value of the first behavior N, K, and M of the input file Input4.DAT (1 ≤ N, K, M ≤ 33 ). The second behavior number is S (0 ≤ S ≤ 100), and in the second row, each behavior is a bar code in the Set BC (N, K, M) described in Figure 33-2.

Output Format: Your program should complete the task:
A. Write the output content to the file OUPUT4.DAT. The first line is the number of bar codes in BC (N, K, M.
B. In row S starting from row 2 of OUPUT. DAT, each row is the number of the barcode corresponding to the input file. spaces are used to separate the numbers of two adjacent lines in the input and output data. First, find the number of bar codes. The state transition equation can be easily obtained:

Ans (n, k, m) = sum {ans (n-x, K-1, m)} (1 <= x <= min (m, n-k + 1 ), km> = n) (n> k)
Ans (k, k, m) = 1
Ans (t, k, m) = 0 (t <k)

Then, find the serial number of each bar code. This requires some tips.

*** Note:

For example, 1101000 is used to calculate the serial number.
L [1] = 2, l [2] = 1, l [3] = 1, l [4] = 3
Which are smaller:
First, l [1] <2 (ans [7-1] [3] = 7)
Then l [1] = 2, l [2]> 1 (ans [7-2-2] [2] + ans [7-2-3] [2] = 2 + 1 = 3)
L [1] = 2, l [2] = 1, l [3] <1 (0)
And the values of l [1] = 2, l [2] = 1, l [3] = 1, l [4]> 3 (0)
Therefore, the serial number is 7 + 3 + 0 + 0-1 + 1 = 10.
Others and so on

***

#include<cstdio>#include<iostream>#include<cstring>#include<string>#include<algorithm>using namespace std;int ans[40][40];int n,m,k,num,temp,temp2;int l[40];int s;string s1;int ans2;int dfs(int n,int k){    if(k*m<n)    {        ans[n][k]=0;        return 0;    }    if(n>k)    {        ans[n][k]=0;        for(int i=1;i<=min(m,n-k+1);i++)            if(ans[n-i][k-1]==-1)                ans[n][k]+=dfs(n-i,k-1);            else                ans[n][k]+=ans[n-i][k-1];    }    else if(n==k)        ans[n][k]=1;    else ans[n][k]=0;    return ans[n][k];}int main(){    int i,p,j,j1;    memset(ans,-1,sizeof(ans));    scanf("%d%d%d",&n,&k,&m);    printf("%d\n",dfs(n,k));    scanf("%d",&s);    for(i=1;i<=s;i++)    {        ans2=0;        cin>>s1;        p=0;        num=0;        for(j=0;j<s1.length()-1;j++)        {            p++;            if(s1[j]!=s1[j+1])            {                l[++num]=p;                p=0;            }        }        l[++num]=p+1;        temp=n;        temp2=k;        for(j=1;j<=num;j++)        {            temp2--;            if(j%2==1)                for(j1=1;j1<l[j];j1++)                {                    ans2+=ans[temp-j1][temp2];                }            else                for(j1=l[j]+1;temp-j1>=temp2&&j1<=m;j1++)                {                    ans2+=ans[temp-j1][temp2];                }            temp-=l[j];        }        printf("%d\n",ans2);        //1101110        //1100    }    return 0;}

Paste a piece of other people's code

# Include <cstdio> # include <algorithm> using namespace std; int n, k, m, s, a [100000]; long f [1000] [1000]; char c [100]; int main () {scanf ("% d", & n, & k, & m, & s ); f [0] [0] = 1; for (int I = 1; I <= n; I ++) for (int j = 1; j <= k; j ++) for (int l = 1; l <= min (m, I); l ++) f [I] [j] = f [I] [j] + f [I-l] [J-1]; printf ("% d \ n ", f [n] [k]); for (int I = 1; I <= s; I ++) {scanf ("% s", c ); c [n] = (c [n-1]-'0') ^ 1 + '0'; int ans = 0, sum1 = 0, sum2 = 0, num = 0, p = 1; for (int j = 1 ; J <= n; j ++) if (c [j]! = C [J-1]) a [++ num] = p, p = 1; else p ++; for (int j = 1; j <= num; j ++) {sum2 ++; if (j & 1) for (int l = a [j]-1; l> = 1; l --) ans + = f [n-sum1-l] [k-sum2]; else for (int l = a [j] + 1; l <= m; l ++) ans + = f [n-sum1-l] [k-sum2]; sum1 + = a [j];} printf ("% d \ n", ans );}}View Code

I will post another explanation, which is nothing to use:

Dynamic Planning and search are inextricably linked. Let's look at an example:

I. Problem Description

A bar code is a symbol that appears in turn and starts with a dark bar. Each bar is a number of unit widths. Figure 1 shows a "bar code" containing four "bars. It continues with 1 + 2 + 3 + 1 = 7 unit widths.

In general, BC (n, k, m) is a program that contains all "entries" from: k, and the total width is equal to n Units, the width of each "bar" is a set of "bar codes" of m units. For example, the bar code in Figure 1 belongs to BC (7, 4, 3), not BC (7, 4, 2 ).

0: 1000100 | 8: 1100100

1: 1000110 | 9: 1100110

2: 1001000 | 10: 1101000

3: 1001100

| 11: 1101100

4: 1001110 | 12: 1101110

5: 1011000 | 13: 1110010

6: 1011100 | 14: 1110100

7: 1100010 | 15: 1110110

Figure 1 Figure 2

Figure 2 shows all 16 symbols in the Set BC (, 3. 1 indicates dark, 0 indicates bright. The bar codes in the figure are arranged alphabetically. The number on the left of the colon is the number of the bar code. In Figure 1, the number of a bar code in BC (, 3) is 4.

Input: the first row number of the input file, n, k, m (1 <= n, k, m <= 30 ). Second behavior number s (s <= 100 ). In the second row, each behavior is a "bar code" in the Set BC (n, k, m) described as 1 ".

Output: Number of bar codes in the first BC (n. k, m) in the output file. Each row in the second row is the number corresponding to the "barcode" in the input file.

Input and Output example:

Ii. Analysis

There are two questions. It is easy to see that counting is the basis for finding the serial number, so we should solve the counting problem first. The original question is only given to one instance, that is, a bar code. To solve this problem with a computer, we must first create a mathematical model that can well describe the problem.

The bar code consists of k black and white blocks with black headers. Each block contains at least 1 piece, at most m pieces, and k pieces are combined into n pieces. Therefore, a bar code can be composed of k tuples (x1, x2 ,..., Xk), and 1 ≤ xi ≤ m, SIGMA (I = 1 .. k) xi = n. Correspondingly, any k-tuples that meet the preceding conditions uniquely represent a bar code that meets the conditions. It is easy to prove that the k-tuples and Bar Code meet the one-to-one correspondence relationship. The number of bar codes that meet the conditions is the number of k tuples. That is, the number of integer solutions of the equation Σ (I = 1 .. k) xi = n, 1 ≤ xi ≤ m.

The easiest way to think of this is to search for algorithm 1: Since the value range of xi has been determined, we can leave all xi values empty and then check how many groups of solutions meet the requirements of Σ (I = 1 .. k) xi = n. The program is easy to write, but the complexity is very high. For mk, the algorithm is very inefficient because m and k may all reach 30.

The reason why the search algorithm is inefficient is that it does not make good use of the constraint sigma (I = 1. k) xi = n, but only uses it as a criterion. The easiest way to improve is to require the number of Integer Solutions for equation x1 + x2 + x3 = 4,1 ≤ x1, x2, x3 ≤ 2. If x1 = 1, the equation is converted into x2 + x3 = 4-x1 = 4-1 = 3. If x1 = 2, the equation is converted into x2 + x3 = 2. The number of Integer Solutions of the original equation is the sum of the numbers of integer solutions of the equation x2 + x3 = 3, x2 + x3 = 2. In this way, we will question the number of Integer Solutions for an equation with three unknown numbers to the number of Integer Solutions for an equation with two unknown numbers. And so on, it can finally be used to calculate the number of Integer Solutions for an equation containing an unknown number. It is easy to conclude that the number of Integer Solutions for equation x = n, 1 ≤ x ≤ m is: when 1 ≤ n ≤ m, there is 1 solution. Otherwise, there are 0 solutions.

Easy to write search algorithm 2:

Func Count (k, n): LongInt; {the number of Integer Solutions of Σ (I = 1. k) xi = n, 1 ≤ xi ≤ m}

Begin

If k = 1 then if 1 ≤ n ≤ m then Count: = 1

Else Count: = 0

Else for I: = 1 to m do Inc (Count, Count (K-1, n-I )){***}

End;

K. the time complexity of the program is still m, but we can reduce the complexity to O (N) by improving the {***} sentence ),

Where N is the return value of the Count function, that is, the number of integer solutions of the equation. The specific method is to modify the starting and ending values of the loop statement: for I: = MinI to MaxI do Inc (Count, Count (K-1, n-I); where, minI = Max {1, n-m * (k-1)}, MaxI = Min {m, n-k + 1 }. The number of integer solutions of the equation can reach 6*10 or higher. Obviously, this program is not efficient. The reason is that the mathematical model is not abstract.

The model of the number of integer solutions of the equation is further abstracted as the sum of k numbers between 1. m and n. The new model does not seem to be different from the integer solution number model of the equation. It just abstracts the unknown number xi in the original model into k numbers. But in fact, this small change can greatly optimize the program: We use F (k, n) to represent k

1. The sum of numbers between. m and the number of n solutions obviously have Equations

F (k, n) = sigma (I = 1. m) F (K-1, n-I ).

And initial condition: If I = 0, F (0, I) = 0, F (0, 0) = 1.

It is easy to write a dynamic planning program:

Proc Count;

Begin

FillChar (F, Sizeof (F), 0 );

F [0, 0]: = 1;

For I: = 1 to n do

For j: = 1 to k do

For p: = 1 to m do

If I> = p then Inc (F [I, j], F [I-p, J-1])

End;

The time complexity of the dynamically planned program is O (n * k * m) ≤ 30*30*30 = 27000.

One of the characteristics of dynamic planning is that it is fast, and the other is that it enriches the computing results. For example, in this question, we not only calculate the number of bar codes for the question, but also calculate all the components consisting of I, each of which contains at least 1 and at most m, the number of bar codes with a total of j I blocks (1 ≤ I ≤ k, 1 ≤ j ≤ n ). This information can easily solve the second question of this question.

To calculate the number of a bar code, you can first count the number of bars smaller than the bar code in the dictionary order. This is easy to do. The specific procedure is as follows:

Func Index (n, k, p: Integer): LongInt;

Begin

If k <= 1 then Index: = 1 else begin

X: = 0;

If Odd (p) then begin q: = 1; Delta: = 1 end else begin q: = m; Delta: =-1 end;

While l [p] <> q do begin

If n> = q then Inc (x, F [n-q, k-1]);

Inc (q, Delta)

End;

8

Inc (x, Index (n-q, K-1, p + 1 ));

Index: = x

End

End;

The L Array stores the k tuples corresponding to the read barcode. For example, the L Array corresponding to bar code 1001110 is L [1] = 1, L [2] = 2, L [3] = 3, L [4] = 1. The time complexity of this process is O (n * k) ≤ 30*30 = 900

After getting the perfect answer, let's take a look at the previous search algorithm. It is easy to see that the search algorithm 2 can be changed:

Func Count (k, n): LongInt; {the number of Integer Solutions of Σ (I = 1. k) xi = n, 1 ≤ xi ≤ m}

Begin

If F [k, n] = NULL then

If k = 0 then F [k, n]: = 1

Else for I: = Max {1, n-m * (k-1)} to Min {m, n-k + 1} do

Inc (F [k, n], Count (K-1, n-I ));

Count: = F [k, n]

End;

The improved algorithm is a recursive method of dynamic planning. This algorithm can be seen as an improvement of the dynamic planning algorithm. Because of the correction of the initial value and end value of decision variable I, the number of computations is less than that of Dynamic Planning in recursive writing. That is to say, we have obtained the same dynamic planning algorithm through the improvement of the search algorithm.

So what is the relationship between dynamic planning and search? Let's look at another question:

Sequential relationship count (Fujian)

I. Problem Description

Use the relationship '<' and '=' to arrange three numbers A, B, and C in 13 different ways:

A <B <C, A <B = C, A <C <B, A = B <C, A = B = C, A = C <B,

B <A <C, B <A = C, B <C <A, B = C <,

C <A <B, C <A = B, C <B <.

Program to find the number of N numbers in order.

Ii. Analysis

<1>. enumerate all sequential relational expressions

We can use the Backtracking Method to enumerate all the sequential relational expressions. A sequential expression of N numbers is composed of N upper-case letters and a N-1 link between each letter. Enumerate uppercase letters and relational symbols at each position until a sequential relational expression is determined.

Because the sequential relational expressions similar to 'a = B 'and' B = A' are equivalent, it is required that the numbers of uppercase letters before the equal signs are in the ASCII table, it must be smaller than the letter number after the equal sign. Based on this idea, we can easily write a backtracking algorithm for this question.

Algorithm 1: calculates the number of ordinal relationships of N numbers.

Procedure Count (Step, First, Can );

{Step indicates that the selected Step is an uppercase letter;

First indicates the minimum value that may be obtained for uppercase letters;

Can is a set. The elements in the set are uppercase letters that Can be used}

Begin

If Step = N then begin {confirm the last letter}

For I: = First to N do if I in Can then Inc (Total); {Total is the result of Statistics}

Exit

End;

For I: = First to N do {enumerative current uppercase letters}

If I in Can then begin {I Can be used}

Count (Step + 1, I + 1, Can-[I]); {Add equal sign}

Count (Step + 1, 1, Can-[I]) {Add to sign}

End

End;

After Count (, [1 .. N]) is called, the value of Total is the result. The time complexity of this algorithm is O (N !)

Figure 4-8 N = 3 answer tree

<2>. Rough use of information and Optimization Algorithm 1

Algorithm 1 has a large number of redundant operations. 4-8, the sub-trees in the three boxes are in the same shape. Once we know the number of sequential relationships generated in a box, we can use this information to directly obtain the number of sequential relationships to be generated in the other two boxes.

Obviously, during the enumeration process, if the number of the first k has been determined, and the next link symbol is less than the number, in this case, the number of sequential relationships that can be generated is the number of sequential relationships that can be generated by the remaining N-k numbers.

Set the number of I to a total of different order relations of F [I]. From the above discussion, we can see that in algorithm 1, Count (Step +, can-[I]), the increment of Total should be F [N-Step]. This value Can be obtained when Count (Step +, Can-[I]) is called for the first time. Once you know the value of F [N-Step], you can use Total: = Total + F [N-Step] instead of calling Count (Step +, can-[I]). In this way, we can get the improved algorithm 1-2.

Algorithm 2: calculates the number of ordinal relationships of N numbers.

Procedure Count (Step, First, Can );

{Step, First, Can has the same meaning as algorithm 1}

Begin

If Step = N then begin {confirm the last letter}

For I: = First to N do if I in Can then Inc (Total); {Total is the result of Statistics}

Exit

End;

For I: = First to N do {enumerate the current uppercase letters

}

Related Article

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.