poj 3734 Blocks 【矩阵快速幂】

Blocks
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 4529 Accepted: 2044
Description

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
Source

PKU Campus 2009 (POJ Monthly Contest – 2009.05.17), Simon

思路:
假设染色第i个方块时,红绿都为偶数方案数ai ,一个奇数一个偶数方案bi,均为奇数方案ci;
则 ai+1 = 2*ai + bi;
bi+1 = 2*ai + 2*bi+2*ci;
ci+1 = 2*ci + bi;
所以可构造矩阵:
2 1 0
2 2 2
0 1 2

代码:

#include <stdio.h>
#include <iostream>
#include <string.h>
#include <algorithm>
#include <math.h>
#include <ctype.h>
#include <time.h>
#include <queue>

using namespace std;

const long long MOD = 10007;

struct node
{
    long long m[3][3];
}ans, base;
long long a, b;

node multi(node a, node b)
{
    node tmp;
    for (int i = 0; i<3; i++)
        for (int j = 0; j<3; j++)
        {
            tmp.m[i][j] = 0;
            for (int k = 0; k<3; k++)
            {
                tmp.m[i][j] = ((tmp.m[i][j] + a.m[i][k] * b.m[k][j]) % MOD + MOD) % MOD;
            }
        }
    return tmp;
}

void fast_mod(int n)// 求矩阵 base 的  n 次幂
{
    base.m[0][0] = 2; base.m[0][1]=1; base.m[0][2] = 0;
    base.m[1][0] = 2; base.m[1][1]=2; base.m[1][2] = 2;
    base.m[2][0] = 0; base.m[2][1]=1; base.m[2][2] = 2;
    memset(ans.m,0,sizeof(ans.m));
    ans.m[0][0] = ans.m[1][1] = 1; ans.m[2][2] = 1;// ans 初始化为单位矩阵
    while (n)
    {
        if (n & 1) //实现 ans *= t; 其中要先把 ans赋值给 tmp,然后用 ans = tmp * t
            ans = multi(ans, base);
        base = multi(base, base);
        n >>= 1;
    }
}

int t;
int n;

int main()
{
    scanf("%d",&t);
    while (t--)
    {
        scanf("%d",&n);
        fast_mod(n);
        long long anss = ((ans.m[0][0] % MOD) + MOD) % MOD;
        printf("%lld\n", anss);
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值