Uva10655 Contemplation! Algebra矩阵快速幂

题目描述:

已知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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值