POJ 3222 Matrix Power Series 【等比矩阵前n项之和(性质 OR 二分?)】

本文介绍了一种解决大规模矩阵幂级数求和问题的方法,通过构造特定矩阵B并利用其性质进行快速计算,适用于k值较大情况下的高效求解。

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

Matrix Power Series
Time Limit: 3000MS Memory Limit: 131072K
Total Submissions: 20879 Accepted: 8735

Description

Given a n × n matrix A and a positive integer k, find the sum S = A + A2 + A3 + … + Ak.

Input

The input contains exactly one test case. The first line of input contains three positive integers n (n ≤ 30), k (k ≤ 109) and m (m < 104). Then follow n lines each containing n nonnegative integers below 32,768, giving A’s elements in row-major order.

Output

Output the elements of S modulo m in the same way as A is given.

Sample Input

2 2 4
0 1
1 1

Sample Output

1 2
2 3

题意:求等比矩阵前n项之和对m取余后的矩阵;

思路:数据量较大,看网上解法有两种,二分的我写超时用数组代替结构体递归函数不好写也没写出来,用等比矩阵的性质写出一种: 

令 B= [
    [A A]
    [0 I]
]

则 B^k = [
    [A^k     A ... A^k]
    [0                    I ]
]

由A构造出矩阵B之后直接上模板就行,用结构体写太麻烦,用数组写了;


失误:这道题写了好久呀,状态还可以,希望自己不要着急;


AC代码:

#include<cstdio>
#include<cstring>

typedef long long LL;
LL ori[77][77],res[77][77];
LL N,mod;

void Mat_mul(LL X[77][77],LL Y[77][77])
{
	LL Z[77][77]; memset(Z,0,sizeof(Z)); 
	LL i=0,j=0,k=0;
	for(i=1;i<=N*2;++i)
	{
		for(k=1;k<=N*2;++k)
		{
			if(X[i][k])
			{
				for(j=1;j<=N*2;++j)
				{
					Z[i][j]+=(X[i][k]*Y[k][j])%mod;
					Z[i][j]%=mod;
				}
			}
		}
	}
	for(i=1;i<=N*2;++i)
	{
		for(j=1;j<=N*2;++j) X[i][j]=Z[i][j]; 
	}
}
void Mat_Q(LL m)
{
	LL i=0;
	memset(res,0,sizeof(res)); 
	for(i=1;i<=2*N;++i) res[i][i]=1;
	while(m)
	{
		if(m&1) Mat_mul(res,ori);
		Mat_mul(ori,ori);
		m>>=1; 
	}
}
int main()
{
	LL K,i,j;
	scanf("%lld %lld %lld",&N,&K,&mod);
	memset(ori,0,sizeof(ori));
	for(i=1;i<=N;++i)
	{
		for(j=1;j<=N;++j)
		{
			scanf("%lld",&ori[i][j]);
			ori[i][j+N]=ori[i][j];
		 } 
	 }
	 for(i=N+1;i<=N*2;++i) ori[i][i]=1;
	 Mat_Q(K);
	 for(i=1;i<=N;++i)
	 {
	 	for(j=N+1;j<=N*2-1;++j)
	 	    printf("%lld ",res[i][j]);
		 printf("%lld\n",res[i][2*N]); 
	 }  
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值