UVA 10655 Contemplation! Algebra

第一直觉是解方程,把a,b都算出来,显然这是不科学的做法,如果a,b都是小数..那就GG了。

正解如下:

计算前几项,可以看出递推式

有了递推式,就可以构造矩阵,进行矩阵快速幂

这题还有2个WA点:

1.这样的数据是合法的:0 0 5,所以最后一组读入的时候并不是p,q都为0就break。

2. n=0的时候需要特判

#include<cstdio>
#include<cstring>
#include<cmath>
#include<vector>
#include<algorithm>
using namespace std;

long long x, y;
int n;

struct Matrix
{
    long long A[5][5];
    int R, C;
    Matrix operator*(Matrix b);
};

Matrix X, Y, Z;

Matrix Matrix::operator*(Matrix b)
{
    Matrix c;
    memset(c.A, 0, sizeof(c.A));
    int i, j, k;
    for (i = 1; i <= R; i++)
        for (j = 1; j <= C; j++)
            for (k = 1; k <= C; k++)
                c.A[i][j] = c.A[i][j] + A[i][k] * b.A[k][j];
    c.R=R; c.C=b.C;
    return c;
}

void init()
{
    n = n - 1;
    Z.A[1][1] = x, Z.A[1][2] = x*x-2*y; Z.R = 1; Z.C = 2;
    Y.A[1][1] = 1, Y.A[1][2] = 0, Y.A[2][1] = 0, Y.A[2][2] = 1; Y.R = 2; Y.C = 2;
    X.A[1][1] = 0, X.A[1][2] = -y, X.A[2][1] = 1, X.A[2][2] = x; X.R = 2; X.C = 2;
}

void work()
{
    while (n)
    {
        if (n % 2 == 1) Y = Y*X;
        n = n >> 1;
        X = X*X;
    }
    Z = Z*Y;

    printf("%lld\n", Z.A[1][1]);
}

int main()
{
    while(scanf("%lld%lld%d",&x,&y,&n)==3)
    {
        if(n==0)
        {
            printf("2\n");
        }
        else{
            init();
            work();
        }
    }
    return 0;
}

 

posted @ 2016-03-02 19:37  Fighting_Heart  阅读(162)  评论(0编辑  收藏  举报