POJ 3233 Matrix Power Series 【矩陣快速冪+等比矩陣】
——————————————————-
Matrix Power Series
Time Limit: 3000MS Memory Limit: 131072K
Total Submissions: 20125 Accepted: 8449
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
————————————————————————————–
題目大意 : 就是求S %m;
題解 : 其實很容易知道A^k 之後只需加和就行了
但是直接加和還是不行 k的範圍是在太大 會超時 所以就構造一個矩陣
因為S可以看成S=A(I+A(I+A(I+…A(I+A)))) (I是單位矩陣)
拿k=3舉例S=A(I+A(I+A))
那麼我們想,可不可以構造一個矩陣T使得T*T(因為是k次冪)這樣乘下去每次可以得到A*(A+I)
那麼肯定T有個兩個元素就是A與I
那麼假設:T={A I }
I I
那麼T=T*T={A*A+I*I A*I+I*I}
A*I+I*I I*I+I*I
這樣存在一個I*(A+I)的式子 ,當T再乘以T的時候會出現A(A+I)
這個時候我們可以簡化將T={A I}
0 I
這樣可以簡化很多計算T*T={A*A A*I+I*I}
0 I
那麼容易得到T^(K+1)={A^(K+1) I+A+A^2+A^3+…+A^K}
0 I
這樣我們只需要算T的k+1次冪就可以了
實在懶得寫這些 其實就是簡單的等比矩陣求和 學過線性代數 就應該能構造出來矩陣的
錯將輸入 n,k,m 當成的 n,m,k 錯了一上午 。。汗2333333333
附本提程式碼
———————————————————————————
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <string>
#include <algorithm>
#include <math.h>
using namespace std;
/******************************/
#define LL long long int
#define _LL __int64
/*****************************/
/*
const int M = 100;
const int MOD = 1e4;
*/
#define M n*2
#define MOD m
LL n,m,k;
struct Matrix
{
// int r,c; //C行R列
LL m[66][66];
};
Matrix operator * (Matrix a,Matrix b)
{
Matrix c;
for(int i=0; i<M; i++) //初始化矩陣
for(int j=0; j<M; j++)
c.m[i][j]= 0;
for(int k=0; k<M; k++)
for(int i=0; i<M; i++) //實現矩陣乘法
{
if(a.m[i][k] <= 0) continue; //剪枝
for(int j=0; j<M; j++)
{
// if(b.m[k][j] <= 0) continue; //剪枝
c.m[i][j]=(c.m[i][j]+a.m[i][k]*b.m[k][j]+MOD)%MOD;
}
}
return c;
}
Matrix operator ^ (Matrix a,LL b)
{
Matrix c;
for(int i=0; i<M; i++) //初始化單位矩陣
for(int j=0; j<M; j++)
c.m[i][j]= ( i == j );
while(b)
{
if(b&1) c= c * a ;
b >>= 1;
a = a * a ;
}
return c;
}
Matrix operator + (Matrix a,Matrix b)
{
for(int i=0; i<M; i++)
for(int j=0; j<M; j++)
a.m[i][j]=(a.m[i][j]+b.m[i][j]+MOD)%MOD;
return a;
}
int main()
{
ios::sync_with_stdio(false);
while( cin>>n>>k>>m )
{
Matrix a;
memset(a.m,0,sizeof(a.m));
for(int i=0; i<n; i++)
for(int j=0; j<n; j++)
cin >> a.m[i][j];
for(int i=0;i<n;i++)
a.m[i+n][i+n]=a.m[i][i+n]=1;
Matrix c;
c = a ^ ( k + 1 );
for(int i=0;i<n;i++) //減掉單位矩陣。。
c.m[i][i+n] = (c.m[i][i+n]-1+MOD)%MOD;
for(int i=0; i<n; i++)
{
for(int j=0; j<n; j++)
{
if(j) cout<<" ";
cout<<c.m[i][j+n];
}
cout<<endl;
}
}
return 0;
}