Queuing HDU - 2604(矩阵快速幂)

本文详细解析了HDU-2604 Queuing题目,介绍了通过动态规划和矩阵快速幂的方法求解特定字符串模式出现次数的问题。给出了完整的C++代码实现,并解释了如何构建转移矩阵。

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

题意:由f, m组成的长度为L的字符串中,子串有"fff"or"fmf"的字符串有K个,输出KmodM的结果;

L           K

 0          1

1          2
2          4
3          6
4          9
5          15
6          25
7          40
8          64
9          104
10          169
11          273
12          441
13          714
14          1156
15          1870
16          3025
17          4895
18          7921
19          12816

由上表可知f[n]=f[n-1]+f[n-3]+f[n-4];

转移矩阵为:


#include <bits/stdc++.h>
using namespace std;
struct node{
	int z[5][5];
};
int L, M;
int f[]={9, 6, 4, 2};
node mul(node a, node b){
	node c;
	for(int i=0; i<4; i++){
		for(int j=0; j<4; j++){
			c.z[i][j]=0;
			for(int k=0; k<4; k++){
				c.z[i][j]=(c.z[i][j]+a.z[i][k]*b.z[k][j])%M;
			}
		}
	}
	return c;
}
int Power(node a, int n){
	node t;
	for(int i=0; i<4; i++){
		for(int j=0; j<4; j++){
			if(i==j) t.z[i][j]=1;
			else t.z[i][j]=0;
		}
	}
	while(n){
		if(n&1) t=mul(t, a);
		a=mul(a, a);
		n>>=1;
	}
	int ans=0;
	for(int i=0; i<4; i++){
		ans=(ans+t.z[0][i]*f[i]%M)%M;
	}
	return ans;
}
int main(){
	while(cin >> L >> M){
		node a;
		memset(a.z, 0, sizeof(a.z));
		a.z[0][0]=a.z[0][2]=a.z[0][3]=a.z[1][0]=a.z[2][1]=a.z[3][2]=1;
		int	ans[]={1, 2, 4, 6, 9};
		if(L<5) cout << ans[L]%M << endl;
		else cout << Power(a, L-4) << endl;
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值