• UVA 10655 Contemplation! Algebra


    题目链接:UVA 10655 Contemplation! Algebra

    题目大意:
    已知(a+b)(ab),求(a^n+b^n)

    题解:
    递推式不难推出来。
    构造矩阵:

    [left(egin{matrix} a^i+b^i \ a^{i-1}+b^{i-1} end{matrix} ight) = left(egin{matrix} a+b & -ab \ 1 & 0 end{matrix} ight) imes left(egin{matrix} a^{i-1}+b^{i-1} \ a^{i-2}+b^{i-2} end{matrix} ight) ]

    所以:

    [left(egin{matrix} a^n+b^n \ a^{n-1}+b^{n-1} end{matrix} ight) = left(egin{matrix} a+b & -ab \ 1 & 0 end{matrix} ight)^{n-1} imes left(egin{matrix} a+b \ 2 end{matrix} ight) ]

    另外,题目规定一行只有两个(0)时结束,但是存在一行有三个数但前两个是(0)的情况,所以不能单纯判断前两个数是不是(0)

    #include <cstdio>
    #include <cstring>
    #include <iostream>
    using namespace std;
    #define ll long long
    
    struct Matrix {  // 矩阵
        int row, col;
        ll num[2][2];
    };
    
    Matrix multiply(Matrix a, Matrix b) {  // 矩阵乘法
        Matrix temp;
        temp.row = a.row, temp.col = b.col;
        memset(temp.num, 0, sizeof(temp.num));
        for (int i = 0; i < a.row; ++i)
            for (int j = 0; j < b.col; ++j)
                for (int k = 0; k < a.col; ++k)
                    temp.num[i][j] = (temp.num[i][j] + a.num[i][k] * b.num[k][j]);
        return temp;
    }
    
    Matrix MatrixFastPow(Matrix base, ll k) {  // 矩阵快速幂
        Matrix ans;
        ans.row = ans.col = 2;
        ans.num[0][0] = ans.num[1][1] = 1;
        ans.num[0][1] = ans.num[1][0] = 0;
        while (k) {
            if (k & 1) ans = multiply(ans, base);
            base = multiply(base, base);
            k >>= 1;
        }
        return ans;
    }
    
    int main() {
        ll p, q, n;
        Matrix base;
        base.row = base.col = 2;
        base.num[1][0] = 1;
        base.num[1][1] = 0;
        while (cin >> p >> q >> n) {
            if (!n) {
                cout << 2 << endl;
                continue;
            }
            base.num[0][0] = p;
            base.num[0][1] = -q;
            Matrix ans = MatrixFastPow(base, n - 1);
            cout << ans.num[0][0] * p + ans.num[0][1] * 2 << endl;
        }
        return 0;
    }
    
  • 相关阅读:
    简明Python3教程 12.问题解决
    简明Python3教程 11.数据结构
    【SPOJ 694】Distinct Substrings
    【codeforces Manthan, Codefest 17 C】Helga Hufflepuff's Cup
    【CF Manthan, Codefest 17 B】Marvolo Gaunt's Ring
    【CF Manthan, Codefest 17 A】Tom Riddle's Diary
    【SPOJ 220】 PHRASES
    【POJ 3261】Milk Patterns
    【POJ 3294】Life Forms
    【POJ 1226】Substrings
  • 原文地址:https://www.cnblogs.com/IzumiSagiri/p/14332227.html
Copyright © 2020-2023  润新知