HDU - 2604 Queuing (递推 + 矩阵快速幂)

思路:

可以找到递推公式f(n)= f(n-1)+f(n-3)+f(n-4)
所以可以构造一个四阶的右乘矩阵来实现递推。
详细方法可以参考类似题型:http://blog.csdn.net/wing_wuchen/article/details/74276372

#include <cstdio>
#include <iostream>
#include <string.h>
#include <queue>
#include <algorithm>
typedef long long int lli;
using namespace std;
int mod;
const int n = 4;
struct mat{
    lli ma[n][n];
};
mat operator * (mat &a,mat &b){
    mat c;
    memset(c.ma,0,sizeof(c.ma));
    for(int k=0;k<n;++k){
        for(int i=0;i<n;++i){
            for(int j=0;j<n;++j){
                c.ma[i][j] += a.ma[i][k]*(b.ma[k][j] % mod) % mod;
            }
        }
    }
    return c;
}
mat qp(mat a,lli k){
    mat c;
    for(int i=0;i<n;++i){
        for(int j=0;j<n;++j){
            c.ma[i][j] = (i==j);
        }
    }
    for(;k;k>>=1){
        if(k&1) c=c*a;
        a = a*a;
    }
    return c;
}


int main(){
    int l;
    while(~scanf("%d%d",&l,&mod)){
        mat a = {1,1,0,0,   0,0,1,0,  1,0,0,1,  1,0,0,0};
        mat b = {9,6,4,2,  0,0,0,0,  0,0,0,0, 0,0,0,0};
        if(l <= 4){
            if(l == 0){
                printf("0\n");
                continue;
            }
            printf("%d\n",b.ma[0][4-l]%mod);
            continue;
        }
        else{
            a = qp(a,l-4);
            b = b * a;
            printf("%d\n",b.ma[0][0]%mod);
        }
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值