UVA 10518 How Many Calls(求计算Fibonacci数列第n项时递归调用次数)

题目链接:
UVA 10518 How Many Calls
分析:
根据公式
Cnt[i]=Cnt[i1]+Cnt[i2]+1 ,且 Cnt[0]=Cnt[1]=1 .
然后用矩阵快速幂构造矩阵解决就行了。
注意:
输出必须用”%lld”输出,用”%I64d”无限WA,简直了。。。。o(╯□╰)o

//0K 0MS
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <iostream>
using namespace std;

long long n,mod,cases=0;

struct Matrix{
    int row,col;
    long long data[10][10];
};

inline void init(Matrix& x)
{
    x.row=x.col=3;
    memset(x.data,0,sizeof(x.data));
    x.data[1][1]=x.data[2][3]=x.data[3][1]=x.data[3][2]=x.data[3][3]=1;
}

inline Matrix multiply(Matrix a,Matrix b)
{
    Matrix ans;
    ans.row=a.row,ans.col=b.col;
    memset(ans.data,0,sizeof(ans.data));
    for(int i=1;i<=ans.row;i++){
        for(int j=1;j<=ans.col;j++){
            for(int k=1;k<=a.col;k++){
                ans.data[i][j]+=a.data[i][k]*b.data[k][j]%mod;
                ans.data[i][j]%=mod;
            }
        }
    }
    return ans;
}

inline Matrix quick_power(Matrix a,long long n)
{
    Matrix ans,tmp=a;
    ans.row=ans.col=a.row;
    memset(ans.data,0,sizeof(ans.data));
    for(int i=1;i<=ans.row;i++)
        ans.data[i][i]=1;
    while(n){
        if(n&1){
            ans=multiply(ans,tmp);
        }
        tmp=multiply(tmp,tmp);
        n>>=1;
    }
    return ans;
}

inline void debug(Matrix x)
{
    for(int i=1;i<=x.row;i++){
        for(int j=1;j<=x.col;j++){
            printf("%lld ",x.data[i][j]);
        }
        printf("\n");
    }
    printf("*****************\n");   
}

int main()
{
    //freopen("Qin.txt","r",stdin);
    //freopen("Qout.txt","w",stdout);
    while(~scanf("%lld %lld",&n,&mod)){
        if(n==0&&mod==0) break;
        if(n==0||n==1){
            printf("Case %lld: %lld %lld %lld\n",++cases,n,mod,1%mod);
            continue;
        }
        Matrix ans,tmp;
        init(ans);
        //debug(ans);
        ans=quick_power(ans,n-1);
        //debug(ans);
        tmp.row=3,tmp.col=1;
        tmp.data[1][1]=tmp.data[2][1]=tmp.data[3][1]=1;
        //debug(tmp);
        tmp=multiply(ans,tmp);
        //debug(tmp);
        printf("Case %lld: %lld %lld %lld\n",++cases,n,mod,tmp.data[3][1]%mod);
    } 
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值