HDU 6030 Happy Necklace【矩阵快速幂】

题目链接

题意:n个点组成的一串序列,点只有红色和蓝色两种。对于序列中的每段连续的素数长度的子串,子串中的红色点的数量不能少于蓝色点的数量。求有多少种排列可能。

因为2是最小的素数,考虑长度为2的子串。红色为A,蓝色为B,则只有AA,AB,BA三种情况。对每种情况,在后面加上A或B,AA可以形成AA,AB,AB可以形成BA,BA可以形成AA。通过这个递推扩展到长度为n的情况,用矩阵快速幂加速即可。矩阵为:


初始情况下,AA,AB,BA都有可能,因此最后将矩阵中的所有数字相加就是答案,注意要模除mod。

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
#define ll long long
const int mod = 1000000000 + 7;
struct Matrix
{
	ll a[5][5];
	void clear()
	{
		for (int i = 1; i <= 3; i++)
			for (int j = 1; j <= 3; j++)	a[i][j] = 0;
	}
	Matrix operator *(const Matrix &b) const
	{
		Matrix tmp;
		tmp.clear();
		for (int i = 1; i <= 3; i++)
			for (int j = 1; j <= 3; j++)
				for (int k = 1; k <= 3; k++)
					tmp.a[i][j] = (tmp.a[i][j] + (a[i][k] * b.a[k][j] % mod)) % mod;
		return tmp;
	}
};

Matrix fast_pow(Matrix tmp, ll n)
{
	Matrix ans;
	ans.a[1][1] = 1; ans.a[1][2] = 0; ans.a[1][3] = 0;
	ans.a[2][1] = 0; ans.a[2][2] = 1; ans.a[2][3] = 0;
	ans.a[3][1] = 0; ans.a[3][2] = 0; ans.a[3][3] = 1;
	while (n)
	{
		if (n & 1)
			ans = ans * tmp;
		n >>= 1;
		tmp = tmp * tmp;
	}
	return ans;
}

int main()
{
	int T;
	scanf("%d", &T);
	while (T--)
	{
		Matrix tmp;
		tmp.a[1][1] = 1; tmp.a[1][2] = 0; tmp.a[1][3] = 1;
		tmp.a[2][1] = 1; tmp.a[2][2] = 0; tmp.a[2][3] = 0;
		tmp.a[3][1] = 0; tmp.a[3][2] = 1; tmp.a[3][3] = 0;
		ll n;
		scanf("%lld", &n);
		if (n == 2)
		{
			printf("3\n");
			continue;
		}
		Matrix tt = fast_pow(tmp, n - 2);
		ll ans = 0;
		ll x = (tt.a[1][1] + tt.a[1][2] + tt.a[1][3]) % mod;
		ll y = (tt.a[2][1] + tt.a[2][2] + tt.a[2][3]) % mod;
		ll z = (tt.a[3][1] + tt.a[3][2] + tt.a[3][3]) % mod;
		printf("%lld\n", (x + y + z) % mod);
	}
	return 0;
}


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值