Matrix Power Series
Matrix Power Series
时间限制(普通/Java):1000MS/3000MS 内存限制:65536KByte
描述
Given a n × n matrix A and a positive integer k, find the sum S = A + A2 + A3 + … + Ak.
输入
The input contains exactly one test case. The first line of input contains three positive integers n (n ≤ 30), k (k ≤ 109) and m (m < 104). Then follow n lines each containing n nonnegative integers below 32,768, giving A’s elements in row-major order.
输出
Output the elements of S modulo m in the same way as A is given.
样例输入
2 2 4
0 1
1 1
样例输出
1 2
2 3
思路
快速幂 加 分治处理数列前一半和后一半
sk=sk/2+sk/2*a^k/2(偶数)
sk=sk/2+sk/2*ak/2+ak(奇数)
AC代码
复制代码
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
- 91
- 92
- 93
- 94
- 95
- 96
using namespace std;
int n,mod;
class Node
{
public:
int a[40][40]={0};
Node operator+(Node &temp)
{
Node res{};
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
res.a[i][j]= (this->a[i][j]+temp.a[i][j])%mod;
}
}
return res;
}
Node operator*(Node &temp)
{
Node res{};
for(int i=1; i<=n; i++)
for(int j=1; j<=n; j++)
{
for(int k=1; k<=n; k++)
res.a[i][j]=(res.a[i][j]+ this->a[i][k]*temp.a[k][j])%mod;
}
return res;
}
}st,yi;
Node quick_pow(int t)
{
Node ans=yi;
Node a=st;
while(t)
{
if(t&1)ans=ans*a;
a=a*a;
t>>=1;
}
return ans;
}
Node dfs(int k)
{
if(k==1)return st;
Node res=dfs(k/2);
Node temp= quick_pow(k/2);
Node b=res;
res=res * temp;
res=res+b;
if(k&1)
{
temp= quick_pow(k);
res=res+temp;
}
return res;
}
void solve()
{
int k;
cin>>n>>k>>mod;
for(int i=1; i<=n; i++)
{
for(int j=1; j<=n; j++)
{
cin>>st.a[i][j];
st.a[i][j]%=mod;
}
}
for(int i=1;i<=n;i++)yi.a[i][i]=1;
Node ans;
ans=dfs(k);
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
if(j!=1)cout<<" ";
cout<<ans.a[i][j];
}
cout<<endl;
}
}
signed main()
{
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
long long _=1;
// cin>>_;
while(_--)
{
solve();
}
}
本文作者:Minza
本文链接:https://www.cnblogs.com/minz-io/p/17632852.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步