HDU 1575 Tr A

Tr A

Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 1769    Accepted Submission(s): 1302


Problem 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
 

Author
xhd
 

Source
HDU 2007-1 Programming Contest
 

Recommend
linle


#include

struct  Matrix
{
    int s[15][15];
};

Matrix A,B,D;
int n;

Matrix mul (Matrix A, Matrix B)
{
	Matrix s;
	int i, j, k;
	for(i = 1; i <= n; i++)
		for(j = 1; j <= n; j++)
		{
			s.s[i][j] = 0;
			for(k = 1; k <= n; k++)
				s.s[i][j] =(s.s[i][j] + A.s[i][k] * B.s[k][j]) % 9973;
		}

		return s;
}
//矩阵快速幂
Matrix pow (Matrix A, int k)
{
	Matrix s = D;
	while(k)
	{
		if(k & 1)  s = mul(A, s);

		A = mul(A,A);

		k = k>>1;
	}
	return s;
}

int main ()
{
	int T;
	scanf("%d", &T);
	while(T--)
	{
		int k;
		int i, j;
		
		scanf("%d %d", &n, &k);
		for(i = 1; i <= n; i++)
			for(j = 1; j <= n; j++)
			{
				D.s[i][j] = (i == j) ;
				scanf("%d", &A.s[i][j]);
			}

			A = pow(A,k);
			int sum = 0;

			for(i = 1; i <= n; i++)
			  sum = (sum + A.s[i][i]) % 9973;

			printf("%d\n", sum);
	}
	return 0;
}




你可能感兴趣的:(ACM-矩阵)