uva10655(矩阵快速幂)

来源:互联网 发布:河北省中标数据网 编辑:程序博客网 时间:2024/06/03 18:08

题意:给你a+b,a*b的值让你求a^n+b^n

题解:a^2+b^2 = (a+b)*(a+b)-2*ab    a^3+b^3 = (a^2+b^2)(a+b)-(a+b)ab

设f(n) = a^n+b^2那么就可以得到递推公式

f(n) = f(n-1)*(a+b)-f(n-2)*ab

最后跑个矩阵快速幂即可

#include<iostream>#include<cstdio>#include<algorithm>#include<cstring>using namespace std;typedef long long ull;struct mat{    ull a[2][2];    mat operator*(const mat &y){        mat z;        for(int i = 0; i < 2; i++)            for(int j = 0; j < 2; j++){                z.a[i][j] = 0;                for(int k = 0; k < 2; k++)                    z.a[i][j] += a[i][k]*y.a[k][j];            }        return z;    }};ull p,q,n;mat quick(ull n){    n--;    mat ans = {p,0,2,0};    mat x = {p,-q,1,0};    while(n){        if(n&1) ans = x*ans;        x = x*x;        n/=2;    }    return ans;}int main(){  //  freopen("in.txt","r",stdin);    while(scanf("%lld%lld%lld", &p, &q, &n) == 3 && p + q + n){        if(n==0){            puts("2");            continue;        }        mat ans = quick(n);        printf("%lld\n",ans.a[0][0]);    }    return 0;}