Tri Tiling (poj2663)

DescriptionIn
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 Input2
8
12
-1
Sample Output3
153
2131
思路:
①a[0]=1;
②把2塊看成一個整體,兩塊的情況下只有3種情況,a[2]=3;
③4塊的時候:如果都是2塊2塊可分割的,那麼a[4]=3a[2]=9;但是如果這4塊不可分割,就有2種情況,a[4]=a[4]+2a[0]=11;
④6塊的時候:加上的這兩塊有3種情況,如果和另外4塊是可分割的,那麼a[6]=3a[4]=33,如果這兩塊和靠近它們的那兩塊是不可分割的,也就是4塊都不可分割,兩種情況,最左邊還有個3種情況的a[2],所以a[6]=a[6]+2a[2]=39,如果6塊都不可分割,又多了2種情況,即a[6]=a[6]+2a[0]=41;
這樣遞推下去式子就出來了:a[n]=3
a[n-2]+2*(a[n-4]+a[n-6]+…+a[0]);
代碼:

#include<iostream>
#include<cstring>
using namespace std;
int main()
{
    int n;
    int a[31];
    while(1){
    cin>>n;
    memset(a,0,sizeof(a));
    if(n==-1){return 0;}
    a[0]=1;
    for(int i=2;i<=n;i+=2)
    {
        a[i]=3*a[i-2];
        for(int j=i-4;j>=0;j-=2){
            a[i]+=2*a[j];
        }
    }
    cout<<a[n]<<endl;
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章