Contemplation! Algebra 矩阵快速幂

Given the value of a+b and ab you will have to find the value of a n + b n Input The input file contains several lines of inputs. Each line except the last line contains 3 non-negative integers p, q and n. Here p denotes the value of a+b and q denotes the value of ab. Input is terminated by a line containing only two zeroes. This line should not be processed. Each number in the input file fits in a signed 32-bit integer. There will be no such input so that you have to find the value of 00 . Output For each line of input except the last one produce one line of output. This line contains the value of a n + b n. You can always assume that a n + b n fits in a signed 64-bit integer.

Sample Input

10 16 2 7 12 3 0 0

Sample Output

68 91

 

#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<queue>
#include<vector>
#include<cmath>
#include<map>
#include<stack>
#include<set>
#include<string>
using namespace std;
typedef long long  LL;
typedef unsigned long long ULL;
#define MAXN 49
#define MOD 10000007
#define INF 1000000009
const double eps = 1e-9;
/*
矩阵快速幂!
an = p an - q an-1
*/
LL p, q, n;
struct Mat
{
    Mat()
    {
        memset(a, 0, sizeof(a));
    }
    LL a[2][2];
    Mat operator * (const Mat& rhs)
    {
        Mat ret;
        for (int i = 0; i < 2; i++)
        {
            for (int j = 0; j < 2; j++)
            {
                if (a[i][j])
                {
                    for (int k = 0; k < 2; k++)
                        ret.a[i][k] += a[i][j] * rhs.a[j][k];
                }
            }
        }
        return ret;
    }
};
Mat fpow(Mat m, LL b)
{
    Mat tmp = m, ans;
    ans.a[1][1] = ans.a[0][0] = 1;
    while (b != 0)
    {
        if (b & 1)
            ans = tmp * ans;
        tmp = tmp * tmp;
        b /= 2;
    }
    return ans;
}
int main()
{
    while (scanf("%lld%lld%lld", &p, &q, &n) == 3)
    {

        LL a1 = p, a2 = p*p - 2 * q;
        if (n == 0)
            printf("2\n");
        else if (n == 1)
            printf("%lld\n", a1);
        else if (n == 2)
            printf("%lld\n", a2);
        else
        {
            n = n - 2;
            Mat M;
            M.a[0][0] = p, M.a[0][1] = -q, M.a[1][0] = 1;
            M = fpow(M, n);
            printf("%lld\n", M.a[0][0] * a2 + M.a[0][1] * a1);
        }
    }
}

 

转载于:https://www.cnblogs.com/joeylee97/p/7258297.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值