【矩阵快速幂】 POJ - 3734 Blocks

Blocks  POJ - 3734 

Panda has received an assignment of painting a line of blocks. Since Panda is such an intelligent boy, he starts to think of a math problem of painting. Suppose there are N blocks in a line and each block can be paint red, blue, green or yellow. For some myterious reasons, Panda want both the number of red blocks and green blocks to be even numbers. Under such conditions, Panda wants to know the number of different ways to paint these blocks.

Input

The first line of the input contains an integer T(1≤T≤100), the number of test cases. Each of the next T lines contains an integer N(1≤N≤10^9) indicating the number of blocks.

Output

For each test cases, output the number of ways to paint the blocks in a single line. Since the answer may be quite large, you have to module it by 10007.

Sample Input

2
1
2

Sample Output

2
6
本题中,设红绿都为偶数是a[i],红绿中有一个奇数是b[i],红绿都为奇数是c[i]
所以a[i+1]=a[i]*2+b[i]
    b[i+1]=a[i]*2+b[i]*2+c[i]*2
    c[i+1]=b[i]+c[i]*2


#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int mod=10007;

struct node
{
    int a[3][3];
};

node matrix(node x,node y)
{
    node c;
    memset(c.a,0,sizeof(c.a));
    for(int i=0;i<3;i++)
    {
        for(int j=0;j<3;j++)
        {
            for(int k=0;k<3;k++)
            {
                c.a[i][j]=(c.a[i][j]+x.a[i][k]*y.a[k][j])%mod;
            }
        }
    }
    return c;
}

int quickpow(node r,int n)
{
    node x;//构造矩阵x
    x.a[0][0]=2,x.a[0][1]=1,x.a[0][2]=0;
    x.a[1][0]=2,x.a[1][1]=2,x.a[1][2]=2;
    x.a[2][0]=0,x.a[2][1]=1,x.a[2][2]=2;
    while(n)
    {
        if(n%2) r=matrix(r,x);
        x=matrix(x,x);
        n/=2;
    }
    return r.a[0][0]%mod;
}

int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        int n;
        scanf("%d",&n);
        node r;  //r为初始矩阵
        for(int i=0;i<3;i++)
        {
            for(int j=0;j<3;j++)
            {
                if(i==j) r.a[i][j]=1;
                else r.a[i][j]=0;
            }
        }
        int ans=quickpow(r,n);
        printf("%d\n",ans);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41037114/article/details/81392975