hdu 1757 A Simple Math Problem

来源:互联网 发布:ppt数据图表怎么做 编辑:程序博客网 时间:2024/06/06 18:36


http://acm.hdu.edu.cn/showproblem.php?pid=1757

Lele now is thinking about a simple function f(x).

If x < 10 f(x) = x.
If x >= 10 f(x) = a0 * f(x-1) + a1 * f(x-2) + a2 * f(x-3) + …… + a9 * f(x-10);
And ai(0<=i<=9) can only be 0 or 1 .

Now, I will give a0 ~ a9 and two positive integers k and m ,and could you help Lele to caculate f(k)%m.

盗用一张图:


#include <stack>#include <stdio.h>#include <string.h>#include <iostream>#include <algorithm>using namespace std;int k,m,f[10] = {9, 8, 7, 6, 5, 4, 3, 2, 1, 0};struct matrix {    int M[12][12];} A,E,B;matrix multiplication(matrix a, matrix b) {    matrix c;    for(int i=0; i<10; i++)        for(int j=0; j<10; j++) {            c.M[i][j] = 0;            for(int k=0; k<10; k++)                c.M[i][j] += (a.M[i][k] * b.M[k][j]);            c.M[i][j] %= m;        }    return c;}matrix quickpow(int x) {    matrix p = E, q = A;    while(x >= 1) {        if(x & 1)   p = multiplication(p, q);        x >>= 1;        q = multiplication(q, q);    }    return p;}int main() {//    freopen("in.txt", "r", stdin);    for(int i=0; i<10; i++)        for(int j=0; j<10; j++) {            if(i == j)  E.M[i][j] = 1;            else E.M[i][j] = 0;        }    while(scanf("%d%d",&k,&m) == 2) {        for(int i=0; i<10; i++) {            int tmp;            scanf("%d",&tmp);            A.M[0][i] = tmp;        }        for(int i=1; i<10; i++)            for(int j=0; j<10; j++) {                if(j == i - 1)  A.M[i][j] = 1;                else    A.M[i][j] = 0;            }        if(k < 10) {            cout << k % m << endl;            continue;        }        matrix res = quickpow(k - 9);        int ans = 0;        for(int i=0; i<10; i++){            ans += res.M[0][i] * (10 - i - 1);            ans %= m;        }        printf("%d\n",ans);    }    return 0;}

0 0
原创粉丝点击