矩阵快速幂uva10655

来源:互联网 发布:淘宝买家订单数据诈骗 编辑:程序博客网 时间:2024/06/06 19:45

思路:

p=a+b;
q=a*b;
 
f[0]=2;
f[1]=a+b;
f[2]=a^2+b^2=(a+b)*(a+b)-2*a*b=(a+b)*f[1]-a*b*f[0];
...
f[n]=a^n+b^n=(a^(n-1)+b^(n-1))*(a+b)-a*b*(a^(n-2)+b^(n-2))=p*f[n-1]-q*f[n-2]
得到矩阵:
|f(n)    | = |a+b  -ab|^(n-1)   |f(n-1)|
|f(n-1)|     |1          0|           * |f(n-2)|

#include<iostream>#include<cstdio>#include<cstring>#include<algorithm>using namespace std;typedef long long LL;const int maxn=4;int p,q,n;struct Matrix{    LL mat[maxn][maxn];    Matrix(){memset(mat,0,sizeof(mat));}    Matrix operator*(const Matrix &a)const    {        Matrix res;        for(int i=0;i<2;i++)        {            for(int j=0;j<2;j++)                for(int k=0;k<2;k++)                res.mat[i][j]+=mat[i][k]*a.mat[k][j];        }        return res;    }};Matrix pow_mul(Matrix &a,int x){    Matrix res;    res.mat[0][0]=res.mat[1][1]=1;    while(x)    {        if(x&1)res=res*a;        a=a*a;        x>>=1;    }    return res;}int main(){    //freopen("in.txt","r",stdin);    while(cin>>p>>q>>n)    {        if(n==0)        {            printf("2\n");            continue;        }        Matrix A,B;        A.mat[0][0]=p;A.mat[0][1]=-q;        A.mat[1][0]=1;A.mat[1][1]=0;        A=pow_mul(A,n-1);        B.mat[0][0]=p;B.mat[1][0]=2;        A=A*B;        printf("%lld\n",A.mat[0][0]);    }    return 0;}


0 0
原创粉丝点击