LIGHT OJ1070 Algebraic Problem

题目:
Given the value of a+b and ab you will have to find the value of a^n+b^n. a 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.

大意:
给定数字a,b的乘积q,a与b的和p;求(a^n+b^n)%2^64;

解法:
直接用unsigned long long 可以解决%2^64的问题,剩下直接套用矩阵快速幂求解;

代码如下:

#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#define maxn 100007
using namespace std;
typedef unsigned long long ull;
struct mat
{
    ull val[5][5];
};
mat matmult(mat a,mat b)
{
    mat ms;
    memset(ms.val,0,sizeof(ms.val));
    for(int i=1;i<=2;i++)
    {
        for(int j=1;j<=2;j++)
        {
            for(int k=1;k<=2;k++)
            {
                ms.val[i][j]+=a.val[i][k]*b.val[k][j];
            }
        }
    }
    return ms;
}
mat matpow(mat a,ull k)
{
    mat ans;
    memset(ans.val,0,sizeof(ans.val));
    for(int i=1;i<=2;i++)
        ans.val[i][i]=1;
    while(k)
    {
        if(k&1)
            ans=matmult(a,ans);
        a=matmult(a,a);
        k>>=1;
    }
    return ans;
}
int main()
{
    int t;
    scanf("%d",&t); 
    int cas=0;
    while(cas<t)
    {
        cas++;
        ull p,q,n;
        scanf("%llu%llu%llu",&p,&q,&n);
        mat ans;
        if(n==0)
        {
            printf("Case %d: ",cas);
            puts("2");
            continue;
        }
        if(n==1)
        {
            printf("Case %d: %llu\n",cas,p);
            continue;
        }
        ans.val[1][1]=p;
        ans.val[2][1]=1;
        ans.val[1][2]=-q;
        ans.val[2][2]=0;
        ans=matpow(ans,n-1);
        ull res=ans.val[1][1]*p+ans.val[1][2]*2;
        printf("Case %d: %llu\n",cas,res);
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值