Tr A 矩阵快速幂

Tr A
Time Limit:1000MS     Memory Limit:32768KB     64bit IO Format:%I64d & %I64u

Description

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<bits/stdc++.h>    
#include<iostream>      
#include<cstdio>      
#include<cstdlib>      
#include<cstring>      
#include<string>      
#include<queue>      
#include<algorithm>      
#include<map>      
#include<iomanip>   
#define inf 0x3f3f3f3f      
#define maxn 11
#define maxm 10000
using namespace std;
struct Matrix {
	int ma[maxn][maxn];
};
int n,k;
const int mod = 9973;
Matrix multi(Matrix a, Matrix b) {
	Matrix ans;
	memset(ans.ma, 0, sizeof(ans.ma));
	for(int i=1; i<=n; ++i) {
		for(int j=1; j<=n; ++j) {
			for(int k=1; k<=n; ++k) {   //矩阵乘法
				ans.ma[i][j] = (ans.ma[i][j] + a.ma[i][k] * b.ma[k][j]%mod) % mod; 
			}
		}
	}
	return ans;
}

Matrix fastm(Matrix a, int x) {
	Matrix ans;
	memset(ans.ma, 0, sizeof(ans.ma));
	for(int i=1; i<=n; ++i)
		ans.ma[i][i] = 1;
	while(x) {                             //矩阵快速幂
		if(x & 1)
			ans = multi(ans, a);
		a = multi(a, a);
		x = x>>1;
	}
	return ans;
}
int main()
{
	int t;
	Matrix ans;
	scanf("%d",&t);
	while(t--) {
		scanf("%d%d",&n,&k);
		for(int i=1; i<=n; ++i)
			for(int j=1; j<=n; ++j)
				scanf("%d",&ans.ma[i][j]);
		
		ans = fastm(ans,k);
		int sum = 0;
		for(int i=1; i<=n; ++i)
			sum = (sum + ans.ma[i][i]) % mod;
		printf("%d\n",sum);
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值