51nod 1013 3的幂的和

题目:传送门

思路:求这样一个公式3^0 + 3^1 +…+ 3^(N) mod 1000000007,简单的计算可以得出f(n)=f(n-1)*3+1。这个递推公式可以用矩阵来做,然后用快速幂得出答案。构造这样一个矩阵 3101 ,答案在矩阵的左下角。

当N=0时: 3101=3101 ,ans=1;

当N=0时: 31013101=9401 ,ans=4;

当N=2时: 310131013101=271301 ,ans=13;

当N=3时: 3101310131013101=814001 ,ans=40;

……

下面是代码:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#define LL long long
#define MOD 1000000007
using namespace std;

struct Node{
    LL x[2][2];
    Node(){
        x[0][0]=x[0][1]=x[1][0]=x[1][1]=0;
    }
    Node(LL a,LL b,LL c,LL d){
        x[0][0]=a;
        x[0][1]=b;
        x[1][0]=c;
        x[1][1]=d;
    }
};

Node mul(Node a,Node b)
{
    Node ans;
    for(int i=0;i<2;i++)
        for(int j=0;j<2;j++)
            for(int k=0;k<2;k++)
                ans.x[i][j]+=a.x[i][k]*b.x[k][j]%MOD,ans.x[i][j]%=MOD;
    return ans;
}

Node quickPow(Node a,LL b)
{
    Node ans=Node(3,0,1,1);
    while(b)
    {
        if(b&1) ans=mul(ans,a);
        a=mul(a,a);
        b>>=1;
    }
    return ans;
}

int main()
{
    LL n;
    Node t=Node(3,0,1,1);
    while(~scanf("%lld",&n))
    {
        Node ans=quickPow(t,n);
        printf("%lld\n",ans.x[1][0]);
    }
} 

猜你喜欢

转载自blog.csdn.net/cyf199775/article/details/75911895