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代码
#include <bits/stdc++.h>
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();
}
}