码迷,mamicode.com
首页 > 其他好文 > 详细

洛谷 P3390 【模板】矩阵快速幂 题解

时间:2017-10-20 21:41:56      阅读:474      评论:0      收藏:0      [点我收藏+]

标签:正文   元素   org   链接   运算   nbsp   oid   描述   tor   

此文为博主原创题解,转载时请通知博主,并把原文链接放在正文醒目位置。

题目链接:https://www.luogu.org/problem/show?pid=3390

题目背景

矩阵快速幂

题目描述

给定n*n的矩阵A,求A^k

输入输出格式

输入格式:

第一行,n,k

第2至n+1行,每行n个数,第i+1行第j个数表示矩阵第i行第j列的元素

输出格式:

输出A^k

共n行,每行n个数,第i行第j个数表示矩阵第i行第j列的元素,每个元素模10^9+7

输入输出样例

输入样例#1:
2 1
1 1
1 1
输出样例#1:
1 1
1 1

说明

n<=100, k<=10^12, |矩阵元素|<=1000 算法:矩阵快速幂

 

重载运算符,然后这题就变成了普通快速幂..美滋滋~

 

AC代码:

 1 #include<cstdio>
 2 #include<cstring>
 3 #include<cmath>
 4 #include<algorithm>
 5 
 6 const int MOD = 1e9+7;
 7 
 8 long long n,k;
 9 
10 struct Matrix
11 {
12     long long a[105][105];
13     
14     Matrix(){
15         memset(a,0,sizeof(a));
16     }
17     
18     Matrix operator * (const Matrix &x)const
19     {
20         Matrix r;
21         for(int i = 1;i <= n;++ i)
22             for(int j = 1;j <= n;++ j){
23                 r.a[i][j] = 0;
24                 for(int k = 1;k <= n;++ k)
25                     r.a[i][j] = (r.a[i][j]+a[i][k]*x.a[k][j]%MOD)%MOD;
26             }
27                 
28         return r;
29     }
30 }ans,base;
31 
32 void ksm()
33 {
34     ans = base;
35     for(long long b = k-1;b;b >>= 1LL)
36     {
37         if(b&1){
38             for(int i = 1;i <= n;++ i)
39             {
40                 for(int j = 1;j <= n;++ j)
41                     printf("%lld ",ans.a[i][j]);
42                 printf("\n");
43             }
44             ans = ans*base;
45         }
46             
47         base = base*base;
48     }
49 }
50 
51 int main()
52 {
53     scanf("%lld%lld",&n,&k);
54     for(int i = 1;i <= n;++ i)
55         for(int j = 1;j <= n;++ j)
56             scanf("%lld",&base.a[i][j]);
57     ksm();
58     for(int i = 1;i <= n;++ i)
59     {
60         for(int j = 1;j <= n;++ j)
61             printf("%lld ",ans.a[i][j]);
62         printf("\n");
63     }
64         
65     return 0;
66 }

 

洛谷 P3390 【模板】矩阵快速幂 题解

标签:正文   元素   org   链接   运算   nbsp   oid   描述   tor   

原文地址:http://www.cnblogs.com/shingen/p/7701247.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!