矩陣快速冪取模
Description
Given a n × n matrix A and a positive integer k, find the sum
S=A+A2+A3+…+Ak.
Input
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
Output the elements of S modulo m in the same way as A is given.
Sample Input
2 2 4
0 1
1 1
Sample Output
1 2
2 3
分析
一上來就使用單純的快速冪,先求
但是這樣還是不夠的,我們來依次列開看看:
發現規律了嗎?
是否發現了什麼?這和快速冪求斐波那契數列是不是很相似?
於是我們可以構造矩陣
接下來看看。
我們就可以求
所以現在需要的就是構造矩陣
構建數組cnt[2*n][2*n],左上角用來存儲矩陣A,右上角和右下角在對角線上預處理爲零,就構造成功了。
最後就是貼上雜亂的代碼了
#include <cstdio>
#include <iostream>
#include <cmath>
#include <cstring>
#include <cstdlib>
#include <string>
#include <queue>
#include <vector>
#include <stack>
#include <algorithm>
#include <set>
#include <map>
using namespace std;
const int N=61;
int ans[N][N];
int a[N][N];
int tmp[N][N];
int cnt[N][N];
int n,m,k;
void fast_mod(int x)
{
memset(ans,0,sizeof(ans));
for (int i=0;i<2*n;i++) //構建單位矩陣
ans[i][i]=1;
while(x)
{
if(x&1)
{
for (int i=0;i<2*n;i++)
for (int j=0;j<2*n;j++)
tmp[i][j]=ans[i][j];
memset(ans,0,sizeof(ans));
for (int i=0;i<2*n;i++)
for (int j=0;j<2*n;j++)
for (int kk=0;kk<2*n;kk++)
ans[i][j]=(ans[i][j]+(tmp[kk][j]*cnt[i][kk])%m)%m;
}
for (int i=0;i<2*n;i++)
for (int j=0;j<2*n;j++)
tmp[i][j]=cnt[i][j];
memset(cnt,0,sizeof(cnt));
for(int i=0;i<2*n;i++)
for (int j=0;j<2*n;j++)
for (int kk=0;kk<2*n;kk++)
cnt[i][j]=(cnt[i][j]+tmp[i][kk]*tmp[kk][j]%m)%m;
x/=2;
}
return ;
}
int main ()
{
while ( scanf ("%d%d%d",&n,&k,&m)!=EOF)
{
memset(a,0,sizeof(a));
memset(cnt,0,sizeof(cnt));
for (int i=0;i<n;i++)
{
for (int j=0;j<n;j++)
{
scanf ("%d",&a[i][j]); //讀入矩陣A
cnt[i][j]=a[i][j]; //左上角填入矩陣A
}
cnt[i][i+n]=1; //右上角對角線
cnt[i+n][i+n]=1; //右下角對角線
}
fast_mod(k+1); //快速冪求解
for (int i=0;i<n;i++) //輸出矩陣的右上角
{
for (int j=0;j<n-1;j++)
{
if(i!=j)
printf ("%d ",(ans[i][j+n]+m)%m); //這裏一定要先+m在%m,防止小於1
else
printf ("%d ",(ans[i][j+n]-1+m)%m); //這裏更加需要+m,減去單位矩陣
}
if(i!=n-1)
printf ("%d\n",(ans[i][2*n-1]+m)%m);
else
printf ("%d\n",(ans[i][2*n-1]-1+m)%m);
}
}
return 0;
}
再次提醒
最後輸出時一定要+m再%m,我是絕不會告訴你,我就是這樣WA了好多次。