UVA 10655 Contemplation! Algebra(构造矩阵和快速幂)

题目链接:
UVA 10655 Contemplation! Algebra
题意:
给出a+b和ab值以及n求出a^n+b^n。数据long long 。
分析:
构造矩阵和快速幂。

| 0    -1  | * | a^(n-2)+b^(n-2) | = | a^(n-1) + b^(n-1) |    
|-ab   a+b |   | a^(n-1)+b^(n-1) |   | a^n + b^n         |
//0K 0MS
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;

struct Matrix{
    int row,col;
    long long data[10][10];
};

inline Matrix multiply(Matrix a,Matrix b)
{
    Matrix ans;
    ans.row=a.row,ans.col=b.col;
    memset(ans.data,0,sizeof(ans.data));
    for(int i=1;i<=ans.row;i++){
        for(int j=1;j<=ans.col;j++){
            for(int k=1;k<=a.col;k++){
                ans.data[i][j]+=a.data[i][k]*b.data[k][j];
            }
        }
    }
    return ans;
}

inline Matrix quick_power(Matrix a,long long n)
{
    Matrix ans,tmp=a;
    ans.row=ans.col=a.row;
    memset(ans.data,0,sizeof(ans.data));
    for(int i=1;i<=ans.row;i++)
        ans.data[i][i]=1;
    while(n){
        if(n&1) ans=multiply(ans,tmp);
        tmp=multiply(tmp,tmp);
        n>>=1;
    }
    return ans;
}

int main()
{
    //freopen("Iin.txt","r",stdin);
    long long p,q,n;
    while(scanf("%lld%lld%lld",&p,&q,&n)==3){
        //printf("p=%lld q=%lld n=%lld\n",p,q,n);
        //一开始while里面写的是~scanf("%lld%lld",&p,&q)&&(p||q),
        //然后在下面写scanf("%lld",&n),这样WA了,o(╯□╰)o。。,输入坑。。。
        if(p==0&&q==0){
            printf("0\n");
            continue;
        }else if(n==0){
            printf("2\n");
            continue;
        }else if(n==1){
            printf("%lld\n",p);
            continue;
        }
        Matrix ans,tmp;
        ans.row=ans.col=2;
        ans.data[1][1]=0,ans.data[1][2]=1;
        ans.data[2][1]=-q,ans.data[2][2]=p;
        tmp.row=2,tmp.col=1;
        tmp.data[1][1]=p,tmp.data[2][1]=p*p-2*q;
        ans=quick_power(ans,n-2);
        tmp=multiply(ans,tmp);
        printf("%lld\n",tmp.data[2][1]);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值