HDU 6030 Happy Necklace (矩阵快速幂)

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=6030

我们只考虑最小的两个素数:2,3

(R代表红色,B代表蓝色)

RR可以组成RRR,RRB(即RR和RB的形式)

RB可以组成RBR(BR的形式)

BR可以组成(BRR的形式)

得到基本矩阵

最小素数为2,所以最终答案矩阵 = quick_pow(基本矩阵,n - 2)

/*
    基本矩阵
    RR  RB BR
RR   1  0  1
RB   1  0  0
BR   0  1  0
*/
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <map>
#include <set>
#include <vector>
using namespace std;
typedef long long ll;
static const int MAX_N = 3e3 + 5;
static const ll Mod = 1e9 + 7;
static const ll INF = (ll)1 << 60;
struct Martix {
	ll mar[3][3];
	Martix() {memset(mar, 0, sizeof(mar));}
};
Martix Mult(Martix a, Martix b) {
	Martix c;
	for (int i = 0; i < 3; ++i) {
		for (int j = 0; j < 3; ++j) {
			for (int k = 0; k < 3; ++k) {
				c.mar[i][j] = (c.mar[i][j] + (a.mar[i][k] * b.mar[k][j]) % Mod) % Mod;
			}
		}
	}
	return c;
}
Martix quick_pow(Martix a, ll n) {
	Martix ret;
	ret.mar[0][0] = ret.mar[1][1]  = ret.mar[2][2] = 1;
	while (n) {
		if (n & 1) ret = Mult(ret, a);
		a = Mult(a, a);
		n >>= 1;
	}
	return ret;
}
int main() {
//	freopen("input.txt", "r", stdin);
//	freopen("output.txt", "w", stdout);
	int T;
	scanf("%d", &T);
	while (T--) {
		ll n;
		scanf("%lld", &n);
		if (n == 2) printf("3\n");
		else {
			Martix tar;
			tar.mar[0][0] = tar.mar[0][2] = tar.mar[1][0] = tar.mar[2][1] = 1;
			tar = quick_pow(tar, n - 2);
			ll res = 0;
			for (int i = 0; i < 3; ++i) {
				for (int j = 0; j < 3; ++j) res = (res + tar.mar[i][j]) % Mod;
			}
			printf("%lld\n", res);
		}
	}
	return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值