hdu 1143

来源:互联网 发布:淘宝教育客户端下载 编辑:程序博客网 时间:2024/06/11 10:17

Description

In how many ways can you tile a 3xn rectangle with 2x1 dominoes? Here is a sample tiling of a 3x12 rectangle. 

Input

Input consists of several test cases followed by a line containing -1. Each test case is a line containing an integer 0 ≤ n ≤ 30. 

Output

For each test case, output one integer number giving the number of possible tilings. 

Sample Input

2812-1

Sample Output

31532131


首先注意:

n=0时,输出1。当n%2==1时,输出0,因为当n为奇数时,是不可能拼成矩形的(因为高始终为3说明每列都需要一个横着的,所以宽一定是2x)。

对于一个长为n>2的矩形,拼法实际分为两大类:1.能够被竖线切割的(即两个两个的看不存在右侧是上(下)面一个横着的,其左下(上)方是个竖着的)。2.不能被竖线切割的。

       

所以第一种情况: f1[n] = f[n - 2] * 3;

第二种情况: 假设将整个矩形分成两个部分,左边边部分为不可用竖线切割状态,则只可能有两种拼法(横着的在上面还是在下面)。所以整个矩形就可以分成 f[n-4]和f[4]、 f[n-6]和f[6]……,因为f[n-6]、f[n-4]……的情况都涵盖在了第一种情况下。则第二种情况:f2[n] = f[n-4]*2 + f[n-6]*2 +...+ f[2]*2 + f[0]*2;

根据加法法则: f[n] = f1[n] + f2[n]

               f[n] = 3*f[n-2] + 2*f[n-4] + ... + f[2]*2 + f[0]*2; ----- ①

            又 f[n-2]=   0     + 3*f[n-4] + ....+ f[2]*2 + f[0]*2; ----- ②

              f[n] = ① - ② = 4*f[n-2] - f[n-4].

代码:

#include<iostream>#include<string.h>using namespace std;int main(){    int n;    __int64 a[35] ,i;    memset(a,0,sizeof(0));    for(a[0]=1 , a[2]=3 , i=4;i<31;i+=2)  a[i]=4*a[i-2]-a[i-4];    while(scanf("%d",&n)!=EOF && n!=-1)    if(n%2) printf("0\n");    else     printf("%I64d\n",a[n]);    return 0;}