AcWing
  • 首页
  • 课程
  • 题库
  • 更多
    • 竞赛
    • 题解
    • 分享
    • 问答
    • 应用
    • 校园
  • 关闭
    历史记录
    清除记录
    猜你想搜
    AcWing热点
  • App
  • 登录/注册

AcWing 205. 斐波那契    原题链接    中等

作者: 作者的头像   Object_ ,  2019-10-21 22:43:35 ,  所有人可见 ,  阅读 1189


2


注意点:

  • 开long long.

#include<cstdio>
#include<iostream>
#include<cstring>
#define ll long long
using namespace std;
const int MOD=10000;
struct Mat{
    ll a[5][5];
    int x,y;//行 列数
    void init(int x_,int y_){
        memset(a,0,sizeof(a));
        x=x_,y=y_;
    }
};
Mat mull(Mat a,Mat b){
    Mat ans;
    ans.init(a.x,b.y);
    for(int x=1;x<=ans.x;x++){
        for(int y=1;y<=ans.y;y++){
            for(int k=1;k<=a.y;k++){
                ans.a[x][y]=(ans.a[x][y]+a.a[x][k]*b.a[k][y])%MOD;
            }
        }
    }
    return ans;
}
Mat poww(Mat a,ll k){
    Mat ans;
    ans.init(a.x,a.y);
    for(int i=1;i<=3;i++)
        ans.a[i][i]=1;
    Mat tmp=a;
    while(k){
        if(k&1)ans=mull(ans,tmp);
        tmp=mull(tmp,tmp);
        k>>=1;
    }
    return ans;
}
int main(){
    while(1){
        ll n;
        scanf("%lld",&n);
        if(n==0){
            printf("0\n");
            continue;
        }
        if(n==-1)break;
        Mat e;//转换矩阵
        e.init(3,3);
        e.a[1][1]=1;
        e.a[1][2]=1;
        e.a[2][1]=1;
        e.a[3][2]=1;
        Mat basic;//初始矩阵
        basic.init(3,1);
        basic.a[1][1]=2;
        basic.a[2][1]=1;
        basic.a[3][1]=1;
        Mat ans=poww(e,n-1);
        ans=mull(ans,basic);
        cout<<ans.a[3][1]<<endl;
    }
    return 0;
}

0 评论

App 内打开
你确定删除吗?
1024
x

© 2018-2025 AcWing 版权所有  |  京ICP备2021015969号-2
用户协议  |  隐私政策  |  常见问题  |  联系我们
AcWing
请输入登录信息
更多登录方式: 微信图标 qq图标 qq图标
请输入绑定的邮箱地址
请输入注册信息