矩阵快速幂模
2019-04-13 12:15发布
生成海报
print?
- #include
- #include
- #include
- #include
- using namespace std;
- #define MAXN 12
- #define M 9973
- typedef struct
- {
- int m[MAXN][MAXN];
- }Matrix;
-
- Matrix a, per;
- int n;
-
- void init()
- {
- for(int i = 0; i < n; i ++)
- for(int j = 0;j < n; j ++)
- {
- scanf("%d", &a.m[i][j]);
- a.m[i][j] = a.m[i][j] % M;
- per.m[i][j] = (i==j);
- }
- }
-
- Matrix multi(Matrix a, Matrix b)
- {
- Matrix c;
- for(int i = 0; i < n; i ++)
- {
- for(int j = 0; j < n; j ++)
- {
- c.m[i][j] = 0;
- for(int k = 0; k < n; k ++)
- {
- c.m[i][j] = c.m[i][j] + a.m[i][k] * b.m[k][j] % M;
- }
- c.m[i][j] = c.m[i][j] % M;
- }
- }
- return c;
- }
-
- int power(int k)
- {
- Matrix c, p, ans = per;
- p = a;
- while(k)
- {
- if(k & 1) ans = multi(ans, p);
- k = k / 2;
- p = multi(p, p);
- }
- int sum = 0;
- for(int i = 0; i < n; i ++)
- {
- sum = (sum + ans.m[i][i]) % M;
- }
- return sum % M;
- }
-
- int main()
- {
- int t, k;
- scanf("%d", &t);
- for(int i = 0; i < t; i ++)
- {
- scanf("%d %d", &n, &k);
- init();
- int ans = power(k);
- printf("%d
", ans);
- }
- return 0;
- }
打开微信“扫一扫”,打开网页后点击屏幕右上角分享按钮