UVA 10655 Contemplation! Algebra

来源:互联网 发布:区域软件 编辑:程序博客网 时间:2024/04/30 04:31

题目链接: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 0x7fffffffint 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
原创粉丝点击