您的位置:首页 > 编程语言 > C语言/C++

poj 3233 Matrix Power Series(二分)

2014-08-01 21:07 501 查看

Matrix Power Series

Time Limit: 3000MS Memory Limit: 131072K
Total Submissions: 14827 Accepted: 6365
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
Sample Output
1 2
2 3

题目描述:求矩阵幂的和。思路:用到了二分的思想,当k为偶数时S=A+A^2+...+A^(k/2)+A^(k/2)(A+A^2+...+A^(k/2)),当k为奇数时S=A+A^2+...+A^(k/2)+A^(k/2)(A+A^2+...+A^(k/2))+A^k,不断分下去,代码WA了好几次,原因是对取模运算不熟悉,这里做一个整理。用C++写了一个矩阵类,代码如下:
/*****************************
(a+b)%mod=(a%mod+b%mod)%mod
(a-b)%mod=(a%mod-b%mod)%mod
(a*b)%mod=(a%mod*b%mod)%mod
a^b%mod=((a%mod)^b)%mod
******************************/
#include<iostream>
#include<stdio.h>
using namespace std;
class Matrix
{
public:
Matrix(int s);
Matrix operator+(const Matrix& b);
Matrix operator%(int mod);
Matrix operator*(const Matrix& b);
friend istream& operator>>(istream& in,Matrix& a);
friend ostream& operator<<(ostream& out,Matrix& a);
void Init();
int n,**A;
};
void Matrix::Init()
{
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)A[i][j]=1;
}
Matrix::Matrix(int s)
{
n=s;
int i,j;
A=new int*[s];
for(i=0; i<s; i++)A[i]=new int[s];
}
Matrix Matrix::operator+(const Matrix& b)
{
Matrix tmp(b.n);
int i,j;
for(i=0; i<b.n; i++)
for(j=0; j<b.n; j++)
tmp.A[i][j]=A[i][j]+b.A[i][j];
return tmp;
}
Matrix Matrix::operator%(int mod)
{
for(int i=0; i<n; i++)
for(int j=0; j<n; j++)
A[i][j]%=mod;
return *this;
}
Matrix Matrix::operator*(const Matrix& b)
{
int i,j;
Matrix tmp(n);
for(i=0; i<n; i++)
for(j=0; j<n; j++)
{
int sum=0;
for(int di=0; di<n; di++)
sum+=A[i][di]*b.A[di][j];
tmp.A[i][j]=sum;
}
return tmp;
}
istream& operator>>(istream& in,Matrix &a)
{
int i,j;
for(i=0;i<a.n;i++)
for(j=0;j<a.n;j++)
in>>a.A[i][j];
return in;
}
ostream& operator<<(ostream& out,Matrix& a)
{
int i,j;
for(i=0;i<a.n;i++)
{
for(j=0;j<a.n;j++)
out<<a.A[i][j]<<' ';
out<<endl;
}
return out;
}
Matrix pow(Matrix a,int b,int mod)
{
if(b==1)return a%mod;
Matrix tmp=pow(a,b/2,mod);
if(b&0x1)return ((tmp%mod*(tmp%mod))%mod*(a%mod))%mod;
return (tmp%mod*(tmp%mod))%mod;
}
Matrix Sum(Matrix a,int b,int mod)
{
if(b==1)return a%mod;
Matrix tmp=Sum(a,b/2,mod);
Matrix t=pow(a,b/2,mod);
if(!(b&0x1))return (tmp%mod+(t%mod)*(tmp%mod))%mod;
return (tmp%mod+(t%mod*(tmp%mod))%mod+pow(a,b,mod)%mod)%mod;
}
int main()
{
int n,k,m;
cin>>n>>k>>m;
Matrix a(n);
cin>>a;
Matrix ans=Sum(a,k,m);
cout<<ans;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  algorithm c++ matrix