Tr A(矩阵快速幂)

A为一个方阵,则Tr A表示A的迹(就是主对角线上各项的和),现要求Tr(A^k)%9973。 

Input

数据的第一行是一个T,表示有T组数据。 
每组数据的第一行有n(2 <= n <= 10)和k(2 <= k < 10^9)两个数据。接下来有n行,每行有n个数据,每个数据的范围是[0,9],表示方阵A的内容。 

Output

对应每组数据,输出Tr(A^k)%9973。

Sample Input

2
2 2
1 0
0 1
3 99999999
1 2 3
4 5 6
7 8 9

Sample Output

2
2686

代码:

#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#include<queue>
#include<stack>
#include<set>
#include<map>
#include<vector>
#include<cmath>


const int maxn =1e5+5;
const int mod =9973;
typedef long long ll;
using namespace std;
struct mat
{
	int a[15][15];
};
int n;
mat Mul(mat a,mat b)
{
	mat ans;
	memset(ans.a,0,sizeof(ans.a));
	for(int t=0;t<n;t++)
	{
		for(int j=0;j<n;j++)
		{
			for(int k=0;k<n;k++)
			{
				ans.a[t][j]=(ans.a[t][j]+a.a[t][k]*b.a[k][j])%mod;
			}
		}
	}
	return ans;
}
mat ans;
ll quickPow(ll x)
{
    mat res;
    memset(res.a,0,sizeof(res));
    for(int t=0;t<n;t++)
    {
    	res.a[t][t]=1;
    }
	while(x)
	{
		if(x&1)
		{
		  	res=Mul(ans,res);
		}
		ans=Mul(ans,ans);
		x>>=1;
	}
	ll ss=0;
	for(int t=0;t<n;t++)
	{
		ss=(ss+res.a[t][t])%mod;
	}
	return ss;
}

int main()
{
	
	int T;
	cin>>T;
    int k;
	while(T--)
	{
		cin>>n>>k;
		for(int t=0;t<n;t++)
		{
			for(int j=0;j<n;j++)
			{
				scanf("%d",&ans.a[t][j]);
			}
		}
		ll s=quickPow(k);
		cout<<s<<endl;
	}
	return 0;
}

 

转载于:https://www.cnblogs.com/Staceyacm/p/10781745.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值