poj2506 Tiling

http://poj.org/problem?id=2506

 

Topic: How many ways can you use 2*1 or 2*2 tiles to lay a 2*n rectangle?

This is a 2*17 rectangle sample.

The input is a sequence of lines, each containing an integer 0 <= n <= 250. For each line of input, output an integer on a separate line giving the number of possible placements of a 2*n rectangle.

 

That is to say, given a 2*n chessboard, cover it with three kinds of squares (2*2, 1*2, 2*1), and find out how many possibilities there are. Through the given case, it can be found that the output The result is too large to store in the long long type, so use the addition of large integers. Drawing can find recursive equations, for 2 * 1, 2 * 2, 2 * 3, there is 1 kind of 2 * 1; 2 * 2 has 3 kinds; 2 * 3 can add a 2 * on the basis of 2 * 2 1 tile placed vertically, add a tile of 2 * 2 on the basis of 2 * 1, or you can add two tiles of 2 * 1 placed horizontally (vertical placement is repeated on the basis of 2 * 2 ). num[3] = num[2]+ 2 * num[1]

 

Algorithm idea: recursive solution, here the iterative method of one-time calculation is used to improve the efficiency of the algorithm. We can find the recursive equation:

1)num[i] = num[i - 1]+ 2 * num[i - 2];  i>2

2)num[0]  =  1 ;  i=0

3)num[1]  =  1 ;  i=1

4)num[2]  =  3 ;  i=2

1 #include <iostream>
 2 #include < string >
 3  using  namespace std;
 4  string Add( string str1, string str2) // Large integer addition (two positive integers) 
5  {
 6      string str;
 7      int len1 = str1. length();
 8      int len2 = str2.length();
 9      if (len1 < len2)     // Add 0 to the front to make the two strings the same length   
10      {
 11          for ( int i = 1; i <= len2 - len1; i++ )
 12              str1 = " 0 " + str1;
 13      }
 14      else 
15      {
 16          for ( int i = 1 ; i <= len1 - len2; i++ )
 17              str2 = " 0 " + str2 ;
 18      }
 19 len1      = str1.length();
 20      int cf = 0 ; // carry 
21      int temp; // current bit value 
22     for (int i = len1 - 1; i >= 0; i--)
23     {
24         temp = str1[i] - '0' + str2[i] - '0' + cf;
25         cf = temp / 10;
26         temp %= 10;
27         str = char(temp + '0') + str;
28     }
29     if (cf != 0)  str = char(cf + '0') + str;
30     return str;
31 }
32 int main()
33 {
34     string num[251] = { "1","1","3" };
35     for (int i = 3; i <= 250; i++)
36     {
37         num[i] = Add(num[i - 1], Add(num[i - 2], num[i-2]));
38     }
39     int temp;
40     while (cin >> temp) {
41         cout << num[temp] << endl;
42     }
43     return 0;
44 }

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325320436&siteId=291194637