1. 程式人生 > >HDU1575-Tr 【矩陣快速冪】(模板題)

HDU1575-Tr 【矩陣快速冪】(模板題)

target bsp .net code test tdi init ace contest

<題目鏈接>

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 
<cstring> #include <iostream> #include <algorithm> using namespace std; const int mod = 9973; struct Matrix { int arr[20][20]; }init,tmp; int n; Matrix Mul(Matrix a, Matrix b) //矩陣相乘 { Matrix temp; for(int i=0;i<n;i++) for (int j = 0; j < n; j++) { temp.arr[i][j]
= 0; for (int k = 0; k < n; k++) { temp.arr[i][j] = (temp.arr[i][j] + a.arr[i][k] * b.arr[k][j] % mod) % mod; } } return temp; } Matrix Pow(Matrix ans, Matrix a, int x) //快速冪 { while (x) { if (x & 1) { ans
= Mul(ans, a); } x >>= 1; a = Mul(a, a); } return ans; } int main() { int t; scanf("%d", &t); while (t--) { int k; scanf("%d%d", &n, &k); for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) { scanf("%d", &init.arr[i][j]); tmp.arr[i][j] = init.arr[i][j]; } Matrix ans=Pow(init, tmp, k - 1); int res = 0; for (int i = 0; i < n; i++) { res = (res + ans.arr[i][i]) % mod; } printf("%d\n", res); } return 0; }


2018-08-08

HDU1575-Tr 【矩陣快速冪】(模板題)