【矩阵快速幂】 Blocks POJ3746

本文介绍了一个有趣的数学问题:熊猫希望给一系列方块上色,要求红色和绿色方块的数量为偶数,探讨了如何计算满足条件的不同涂色方案数量,并提供了一种使用矩阵快速幂的方法来解决该问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

3744:Blocks

总时间限制: 

1000ms

 

内存限制: 

65536kB

描述

Panda has received an assignment of painting a line of blocks. Since Panda is such an intelligent boy, he start 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.

输入

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.

输出

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.

样例输入

2
1
2

样例输出

2
6

来源

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

 

 

#include <iostream>
using namespace std;

const int mn = 1e9 + 10, mod = 10007;

/// 均为偶数 a[i + 1] = 2 * a[i] + b[i];
/// 其中一个为偶数 b[i + 1] = 2 * (a[i] + b[i] + c[i])
/// 均为偶数 c[i + 1] = b[i] + 2 * c[i]
/// 构造矩阵a
int a[3][3] = {{2, 1, 0}, {2, 2, 2}, {0, 1, 2}};

struct node  /// 结构体内保存数组 方便函数递归及计算
{
	int c[3][3];
};

node mul(const node& p, const node& q)
{
	node t;
	for (int i = 0; i < 3; i++)
		for (int j = 0; j < 3; j++)
		t.c[i][j] = 0;

	for (int i = 0; i < 3; i++)  // 矩阵相乘
		for (int j = 0; j < 3; j++)
		for (int k = 0; k < 3; k++)
		t.c[i][j] = (t.c[i][j] + p.c[i][k] * q.c[k][j]) % mod;
	return t;
}

node pow(int n)
{
	node p, q;  /// q = 满足 (q * p = p) 的矩阵
	q.c[0][0] = 1, q.c[0][1] = 0, q.c[0][2] = 0;
	q.c[1][0] = 1, q.c[1][1] = 0, q.c[1][2] = 1;
	q.c[2][0] = 0, q.c[2][1] = 0, q.c[2][2] = 1;
	for (int i = 0; i < 3; i++)
		for (int j = 0; j < 3; j++)
			p.c[i][j] = a[i][j];

	while (n > 0)  // 快速幂
	{
		if (n & 1)
			q = mul(q, p);
		p = mul(p, p);
		n >>= 1;
	}
	return q;
}

int main()
{
	int T;
	scanf("%d", &T);
	while (T--)
	{
		int n;
		scanf("%d", &n);

        node q = pow(n - 1);  // 计算矩阵自身相乘(n - 1)次

        int d[3] = {0};  // 答案矩阵
        int b[3] = {2, 2, 0}; /// 初始矩阵 n = 1时
        for (int i = 0; i < 3; i++)
		{
			for (int j = 0; j < 3; j++)
				d[i] = (d[i] + q.c[i][j] * b[j]) % mod;
		}

		printf("%d\n", d[0]);
	}
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值