首页 > 代码库 > Uva 10655 - Contemplation! Algebra ( 矩阵快速幂 )

Uva 10655 - Contemplation! Algebra ( 矩阵快速幂 )

 

Uva 10655 - Contemplation! Algebra ( 矩阵快速幂 )

 

 

#include <cstdio>#include <cstring>#include <algorithm>using namespace std;typedef long long LL;#define MAX_SIZE 2LL p, q, n, t;LL M[MAX_SIZE];struct Mat{    LL mat[MAX_SIZE][MAX_SIZE];    void init()    {        for( int i = 0; i < 2; ++i )            for( int j = 0; j < 2; ++j )                mat[i][j] = ( i == j );    }    void zero()    {        for( int i = 0; i < 2; ++i )            for( int j = 0; j < 2; ++j )                mat[i][j] = 0;    }    void setv( int v )    {        for( int i = 0; i < 2; ++i )            for( int j = 0; j < 2; ++j )                mat[i][j] = v;    }    Mat operator*( const Mat &b )const    {        Mat c;        c.zero();        for( int k = 0; k < 2; ++k )            for( int i = 0; i < 2; ++i )    if( mat[i][k] )                for( int j = 0; j < 2; ++j )                    c.mat[i][j] = ( c.mat[i][j] + mat[i][k] * b.mat[k][j] );        return c;    }        void debug()    {        for( int i = 0; i < 2; ++i )        {            for( int j = 0; j < 2; ++j )            {                if( j != 0 )    putchar(   );                printf( "%lld", mat[i][j] );            }            putchar( \n );        }    }};Mat fast_mod( Mat a, LL b ){    Mat res;    res.init();    while( b )    {        if( b & 1 )    res = res * a;        a = a * a;        b >>= 1;    }    return res;}void Orz(){    while( scanf( "%lld %lld %lld", &p, &q, &n) == 3 )    {        /******************************/        M[0] = p, M[1] = p * p - 2 * q;        Mat c;        c.mat[0][0] = 0;        c.mat[0][1] = 1;        c.mat[1][0] = -q;        c.mat[1][1] = p;        //c.debug();        /******************************/        if( n == 0 )    puts( "2" );         else if( n == 1 )    printf( "%lld\n", M[0] );        else if( n == 2 )    printf( "%lld\n", M[1] );        else        {            //Mat res = fast_mod( c, n-1 );                Mat res = fast_mod( c, n-2 );                LL ans = res.mat[1][0] * M[0] + res.mat[1][1] * M[1];            printf( "%lld\n", ans );        }            }}int main(){    Orz();        return 0;}
代码君///特别注意输入的判定,,,狂WA N发不解释

 

Uva 10655 - Contemplation! Algebra ( 矩阵快速幂 )