Uva10655 Contemplation! Algebra矩阵快速幂

来源:互联网 发布:mac死机自动重启 编辑:程序博客网 时间:2024/06/06 00:44

题目描述:

已知a + b = p , ab = q , 求a^n + b^n的值,a和b有可能是虚数;

思路:设S(n) = a^n + b^n,则S(n) = a ^ n + b ^ n = (a + b)^(a^(n - 1) + b^(n  - 1)) - a* b^(n - 1) - a ^(n - 1) * b = p * S(n - 1) - ab * (a^(n - 2) + b ^(n - 2)) = p * S(n - 1) - q * S(n - 2)

由此可见,构造矩阵使用快速幂来求解即可

#include <bits/stdc++.h>#define LL long long#define mem(a , x) memset(a , x , sizeof(a))using namespace std;int n;struct Matrix{    LL a[3][3];    Matrix(int x = 0){        mem(a , 0);        for(int i = 1 ; i <= n; i++){            a[i][i] = x;        }    }    Matrix operator+(const Matrix& B){        Matrix res;        for(int i = 1 ; i <= n; i++){            for(int j = 1 ;j <= n ; j++){                res.a[i][j] = a[i][j] + B.a[i][j];            }        }        return res;    }    Matrix operator*(const Matrix& B){        Matrix res;        for(int i = 1 ;i <= n ; i++){            for(int j = 1 ; j<= n;j ++){                for(int k = 1 ; k <= n; k++){                    res.a[i][j] += a[i][k] * B.a[k][j];                }            }        }        return res;    }    Matrix operator^ (int t){        Matrix A = (*this) , res(1);        while(t){            if(t & 1)   res = res * A;            A = A * A;            t >>= 1;        }        return res;    }};int main(){    n = 2;    int N;    LL p , q;    Matrix base , mul;    while(scanf("%lld %lld" , &p , &q) != EOF){        if(scanf("%d" , &N) != 1)   break;        if(N == 0)  puts("2");        else if(N == 1) printf("%d\n" , p);        else if(N == 2) printf("%lld\n" , p * p - 2LL * q);        if(N <= 2)  continue;        base.a[1][1] = p * p - 2LL * q;   base.a[1][2] = p;        base.a[2][1] = p;   base.a[2][2] = 2LL;        mul.a[1][1] = p;    mul.a[1][2] = 1LL;        mul.a[2][1] = -q;    mul.a[2][2] = 0;        int t = N - 2;        Matrix Q = mul^t;        Matrix ans = base * Q;        LL res = ans.a[1][1];        printf("%lld\n" , res);    }    return 0;}


原创粉丝点击