| ||||||||||
| Online Judge | Problem Set | Authors | Online Contests | User | ||||||
|---|---|---|---|---|---|---|---|---|---|---|
| Web Board Home Page F.A.Qs Statistical Charts | Current Contest Past Contests Scheduled Contests Award Contest | |||||||||
矩阵求幂一般涉及矩阵求幂的问题都要求很大的幂,需要快速求出,这就使人想到了二分法。
想到二分法后,首先想到递归:
____ DFS(int a)
{
____ ret1;
if(a==1) return G2;
ret1=DFS(a/2);
ret1=Cheng(ret1,ret1);
if(a%2)ret1=Cheng(ret1,G2);
return ret1;
}
注:____是矩阵结构体的类型,Cheng代表两个矩阵相乘返回的值,DFS函数调用时参数a即为要乘的次数
但是递归毕竟是有函数调用的时间,所以不是很快,于是我们就可以用迭代写出更快的程序:
matrix pow(matrix a,int n)
{
matrix tmp=a,ret=def;
while(n!=0)
{
if((n&1)!=0) ret=ret*tmp;
tmp=tmp*tmp;
n>>=1;
}
return ret;
}
注:def<=>1 0
0 1(单位矩阵)
a代表要求幂的矩阵
Followed by: Post your reply here: |
All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator