UVA 10870 recurrences (math: Matrix fast Power)

Source: Internet
Author: User
Tags mul pow

Give a recursive relationship that allows you to find the nth item in the relationship

It is common to think that recursion with large data can consider using matrix fast power

Here the matrix is no longer described, there is a petition

The code is as follows:

#include <cstdio> #include <cstring> #include <iostream> #include <algorithm> #define MAXN usi

NG namespace Std;
int X[MAXN];
int MOD, n, D; struct Matrix {int M[MAXN][MAXN];}

A, F;
    Matrix Mul (Matrix A, matrix B) {matrix res;
            for (int i=1, i<=d; ++i) {for (int j=1; j<=d; ++j) {res.m[i][j] = 0;
            for (int k=1; k<=d; ++k) {res.m[i][j] = (res.m[i][j]+a.m[i][k]*b.m[k][j]%mod+mod)%mod;
}}} return res;
    } Matrix Pow (matrix A, int b) {Matrix res;
    memset (res.m, 0, sizeof (RES.M));
    for (int i=1; i<=d; ++i) res.m[i][i] = 1;
        while (b) {if (b & 1) res = Mul (res, a);
        A = Mul (A, a);
    b >>= 1;
} return res; } int main (void) {while (~scanf ("%d%d%d", &d, &n, &mod) && (d| | n| |
        MOD) {memset (a.m., 0, sizeof (a.m.));

        memset (f.m, 0, sizeof (F.M)); for (int i=1; i&Lt;=d;
        ++i) scanf ("%d", &x[i]);
        for (int i=1; i<d; ++i) a.m[i][i+1] = 1;
        for (int i=1; i<=d; ++i) {a.m[d][i] = X[d-i+1]%mod;
            } for (int i=1; i<=d; ++i) {scanf ("%d", &f.m[i][1]);
        F.M[I][1]%= MOD;
        } Matrix tmp = Pow (A, n-d);
        Matrix ans = Mul (tmp, F);
    printf ("%d\n", (ans.m[d][1]+mod)%mod);
} return 0; }


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.