您的位置:首页 > 其它

uva 10655 Contemplation! Algebra 矩阵快速幂

2013-08-16 18:41 447 查看
#include <cstdio>
#include <cstring>
#include <cmath>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
#define LL long long
struct matrix{
    LL f[2][2];
};
matrix mul(matrix a,matrix b)
{
    LL i,j,k;
    matrix c;
    memset(c.f,0,sizeof(c.f));
    for(i=0;i<2;i++)
        for(j=0;j<2;j++)
            for(k=0;k<2;k++)
            c.f[i][j]+=a.f[i][k]*b.f[k][j];
    return c;
}
matrix ksm(matrix e,LL n)
{
    matrix s;
    s.f[0][0]=s.f[1][1]=1;
    s.f[0][1]=s.f[1][0]=0;
    while(n)
    {
        if(n&1)
            s=mul(s,e);
        e=mul(e,e);
        n=n>>1;
    }
    return s;
}
matrix e;
int main()
{
    LL p,q,n;
    while(cin>>p>>q>>n)
    {
        /*if(p==0&&q==0)  //??????????? why not?
            break;      
        cin>>n;       
        */
        if(n==0)
        {
            cout<<2<<endl;
            continue;
        }
        e.f[0][0]=p;e.f[0][1]=1;
        e.f[1][0]=-q;e.f[1][1]=0;
        e=ksm(e,n-1);
        LL ans;
        ans=p*e.f[0][0]+2*e.f[1][0];
        cout<<ans<<endl;
    }
    return 0;
}
/*
    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
=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
 f[n-1]|=|f[1] f[0]|*|a+b  1|^(n-1)
                              |-a*b 0|  
    注意:n=0时需要特判
*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: