hdu 1575 Tr A

题目来源:http://acm.hdu.edu.cn/showproblem.php?pid=1575

题意:求矩阵的k次方后主对角线上的和+mod9973

解法:矩阵快速幂的入门题。

总结:感觉矩阵快速幂还挺有趣的,今天开始了解了一下。加油!

 1 #include<iostream>

 2 #include<cstdio>

 3 #include<cstdlib>

 4 #include<cstring>

 5 #include<cmath>

 6 #include<algorithm>

 7 #define inf 0x7fffffff

 8 using namespace std;

 9 int n,k;

10 struct matrix

11 {

12     int an[20][20];

13 };

14 matrix temp;

15 matrix multiply(matrix a,matrix b)

16 {

17     matrix c;

18     memset(c.an,0,sizeof(c.an));

19     for (int i=1 ;i<=n ;i++)

20     {

21         for (int j=1 ;j<=n ;j++)

22         {

23             for (int k=1 ;k<=n ;k++)

24             {

25                 c.an[i][j] += (a.an[i][k]*b.an[k][j])%9973;

26                 c.an[i][j] %= 9973;

27             }

28         }

29     }

30     return c ;

31 }

32 int calc(int u)

33 {

34     matrix x;

35     memset(x.an,0,sizeof(x.an));

36     for (int i=1 ;i<=n ;i++) x.an[i][i]=1;

37     while (u)

38     {

39         if (u & 1) x=multiply(x,temp);

40         u >>= 1;

41         temp=multiply(temp,temp);

42     }

43     int sum=0;

44     for (int i=1 ;i<=n ;i++)

45     {

46         sum += (x.an[i][i])%9973;

47         sum %= 9973 ;

48     }

49     return sum%9973;

50 }

51 int main()

52 {

53     int t;

54     cin>>t;

55     while (t--)

56     {

57         cin>>n>>k;

58         for (int i=1 ;i<=n ;i++)

59         {

60             for (int j=1 ;j<=n ;j++)

61             scanf("%d",&temp.an[i][j]);

62         }

63         printf("%d\n",calc(k));

64     }

65     return 0;

66 }

 

你可能感兴趣的:(HDU)