LOJ 1070 - Algebraic Problem(矩阵快速幂)

题目链接:http://lightoj.com/volume_showproblem.php?problem=1070

 

 

Given the value of a+b and ab you will have to find the value of an+bna and b not necessarily have to be real numbers.

Input

Input starts with an integer T (≤ 10000), denoting the number of test cases.

Each case contains three non-negative integers, p, q and n. Here p denotes the value of a+b and q denotes the value of ab. 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 test case, print the case number and (an+bn) modulo 264.

Sample Input

Output for Sample Input

2

10 16 2

7 12 3

Case 1: 68

Case 2: 91

 

题意:

 

给出a+b的值p,a*b的值q,求an+bn的值!

PS:

 

a^2+b^2 = (a+b)*(a+b) - 2*a*b

a^3+b^3 = (a^2+b^2)*(a+b) - a*b(a+b)

a^4+b^4 = (a^3+b^3)*(a+b) - a*b(a^2+b^2)

所以:F(0) = 2,F(1) = a+b = p;

所以得到F(n) = a^n+b^n

F(n) = F(n-1)*p - F(n-2)*q

 

用 unsigned long long ,llu超过2^64会自动取模。

代码如下:

 

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
#define ULL unsigned long long
struct Matrix
{
    ULL m[3][3];
} I,A,B,T;

int ssize = 2;

Matrix Mul(Matrix a,Matrix b)
{
    int i, j, k;
    Matrix c;
    for(i = 1; i <= ssize; i++)
    {
        for(j = 1; j <= ssize; j++)
        {
            c.m[i][j]=0;
            for(k = 1; k <= ssize; k++)
            {
                c.m[i][j]+=(a.m[i][k]*b.m[k][j]);
            }
        }
    }
    return c;
}

Matrix quickpagow(ULL n)
{
    Matrix m = A, b = I;
    while(n > 0)
    {
        if(n & 1)
            b = Mul(b,m);
        n = n >> 1;
        m = Mul(m,m);
    }
    return b;
}
int main()
{
    ULL p, q;
    ULL a, b, n;
    int t;
    int cas = 0;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%llu%llu%llu",&p,&q,&n);
        memset(I.m,0,sizeof(I.m));
        memset(A.m,0,sizeof(A.m));
        memset(B.m,0,sizeof(B.m));
        for(int i = 1; i <= ssize; i++)
        {
            //单位矩阵
            I.m[i][i]=1;
        }
        A.m[1][1] = p;//初始化等比矩阵
        A.m[1][2] = -q;
        A.m[2][1] = 1;
        B.m[1][1] = p;
        B.m[2][1] = 2;
        if(n == 0)
        {
            printf("Case %d: 2\n",++cas);
            continue;
        }
        T = quickpagow(n-1);//注意n-1为负的情况
        T = Mul(T,B);
        printf("Case %d: %llu\n",++cas,T.m[1][1]);
    }
    return 0;
}

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值