zoukankan      html  css  js  c++  java
  • HDU 2855 (矩阵快速幂)

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2855

    题目大意:求$S(n)=sum_{k=0}^{n}C_{n}^{k}Fibonacci(k)$

    解题思路

    题目挺吓人的。先把完整组合数+Fibonacci展开来。

    利用Fibonacci的特性,从第一项开始消啊消,消到只有一个数:

    $S(0)=f(0)$

    $S(1)=f(2)$

    $S(2)=f(4)$

    $S(n)=f(2*n)$

    这样矩阵快速幂就可以了,特判$n=0$时的情况。

    快速幂矩阵

    $egin{bmatrix}f1 & f0 \ 0 & 0end{bmatrix}egin{bmatrix}1 & 1 \1 & 0 end{bmatrix}=egin{bmatrix}f2 & f1 \
    0 & 0end{bmatrix}$

    代码

    #include "cstdio"
    #include "cstring"
    #define LL long long
    #define mod m
    #define K 2
    LL n,m;
    struct Matrix
    {
        LL mat[K][K];
        Matrix() {memset(mat,0,sizeof(mat));}
        Matrix(LL *val)
        {
            int idx=0;
            for(int i=0;i<K;i++)
                for(int j=0;j<K;j++)
                  mat[i][j]=val[idx++];
        }
    };
    Matrix operator * (Matrix a,Matrix b)
    {
        Matrix ret;
        for(int i=0;i<K;i++)
            for(int j=0;j<K;j++)
        {
            ret.mat[i][j]=0;
            for(int k=0;k<K;k++)
                ret.mat[i][j]+=((a.mat[i][k]*b.mat[k][j])%mod);
        }
        return ret;
    }
    Matrix operator ^ (Matrix a,LL n)
    {
        Matrix ret,base=a;
        for(int i=0;i<K;i++) ret.mat[i][i]=1;
        while(n)
        {
            if(n&1) ret=ret*base;
            base=base*base;
            n>>=1;
        }
        return ret;
    }
    int main()
    {
        //freopen("in.txt","r",stdin);
        int T;
        scanf("%d",&T);
        while(T--)
        {
            scanf("%I64d%I64d",&n,&m);
            if(n==0) printf("0
    ");
            else
            {
                LL obj=n*2;
                LL bval[]={1,0,0,0};
                LL pval[]={1,1,1,0};
                Matrix Base(bval),Pow(pval),ans=Pow^(obj-1);
                ans=Base*ans;
                printf("%I64d
    ",ans.mat[0][0]%mod);
            }
        }
    }
  • 相关阅读:
    BZOJ3932 [CQOI2015]任务查询系统
    数位DP专练
    Codeforces #669 div2
    Codeforces #670 div2
    P1450 [HAOI2008] 硬币购物
    P3172 [CQOI2015]选数
    比赛-Round 1 (12 Jul, 2018)
    “记计帐”需求分析
    一个程序员的哲学思考
    中国式大学——我们需要获得什么?
  • 原文地址:https://www.cnblogs.com/neopenx/p/4543474.html
Copyright © 2011-2022 走看看