[51nod]1668 非010串【矩阵乘法】

1668 非010串

【题目描述】
传送门

【题解】

先求出递推式,然后用矩阵乘法求解。

代码如下

#include<cstdio>
#include<cstring>
#include<iostream>
#define LL long long
using namespace std;
const LL MOD=1e9+7;
LL n;
struct xcw{
    LL a[5][5];
    xcw(){memset(a,0,sizeof(a));}
    xcw operator *(const xcw b){
        xcw c;
        for(int i=1;i<=4;i++)
        for(int j=1;j<=4;j++)
        for(int k=1;k<=4;k++)
        c.a[i][j]=(c.a[i][j]+a[i][k]*b.a[k][j]%MOD)%MOD;
        return c;
    }
    void operator =(const xcw b){
        for(int i=1;i<=4;i++)
        for(int j=1;j<=4;j++) a[i][j]=b.a[i][j];
    }
    void write(){printf("%lld\n",(a[1][1]+a[2][1]+a[3][1]+a[4][1])%MOD);}
}Ans,Tmp;
void qsm(){
    for(;n;n>>=1,Tmp=Tmp*Tmp) if(n&1) Ans=Tmp*Ans;
}
int main(){
    #ifndef ONLINE_JUDGE
    freopen("prob.in","r",stdin);
    freopen("prob.out","w",stdout);
    #endif
    scanf("%lld",&n);
    if(n==1){printf("2\n");return 0;}
    else if(n==2){printf("4\n");return 0;}
    n-=2;
    Ans.a[1][1]=Ans.a[2][1]=Ans.a[3][1]=Ans.a[4][1]=1;
    Tmp.a[1][1]=Tmp.a[1][3]=Tmp.a[2][1]=Tmp.a[2][3]=Tmp.a[3][4]=Tmp.a[4][2]=Tmp.a[4][4]=1;
    qsm();Ans.write();
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41357771/article/details/80444321
今日推荐