UVA 10655 Contemplation! Algebra

题目链接:http://acm.hust.edu.cn/vjudge/problem/41740


题意:给出a+b和ab的值,n,求a^n+b^n。


思路:n可能很大,所以直接考虑矩阵快速幂。

( a^n + b^n )( a + b ) = a^(n+1) + b^(n+1) + ab( a^(n-1) + b^(n-1) )

a^(n+1) + b^(n+1) = ( a^n + b^n )( a + b )  - ab( a^(n-1) + b^(n-1) )

令f(i) = a^i + b^i

f(i+1) = (a+b)fi - ab*f(i-1)


#include <cstdio>
#include <cmath>
#include <cstring>
#include <string>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <stack>
#include <map>
#include <set>
#include <vector>
#include <sstream>
#include <queue>
#include <utility>
using namespace std;

#define rep(i,j,k) for (int i=j;i<=k;i++)
#define Rrep(i,j,k) for (int i=j;i>=k;i--)

#define Clean(x,y) memset(x,y,sizeof(x))
#define LL long long
#define ULL unsigned long long
#define inf 0x7fffffff


int p,q;
int n;

struct matrix
{
    LL a[2][2];
    void init(LL A = 0,LL B = 0,LL C = 0,LL D = 0)
    {
        a[0][0] = A , a[0][1] = B , a[1][0] = C , a[1][1] = D;
    }
    void E()
    {
        a[0][0] = a[1][1] = 1;
        a[1][0] = a[0][1] = 0;
    }
};

matrix multi( matrix & tx , matrix & ty )
{
    matrix ans;
    ans.init();
    rep( i , 0 , 1 )
        rep( j , 0 , 1 )
            rep( k , 0 , 1 )
            ans.a[i][j] =  ( ans.a[i][j] + tx.a[i][k] * ty.a[k][j] ) ;
    return ans;
}

LL solve()
{
    matrix ans,temp;
    temp.init(0,-q,1,p);
    ans.E();
    if ( n == 0 ) return 2;
    if ( n == 1 ) return p;
    while( n )
    {
        if ( n & 1 ) ans = multi( ans , temp );
        temp = multi( temp , temp );
        n >>= 1;
    }
    LL t = ans.a[0][0] * 2 + ans.a[1][0] * p;
    return t;
}
int main()
{
    while( scanf("%d %d",&p,&q) == 2 )
    {
        if (  scanf("%d",&n) != 1 && p + q == 0 ) break;
        printf("%lld\n",solve());
    }
    return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值