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

题目

Queuing

Time Limit: 10000/5000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 7245    Accepted Submission(s): 3198


 

Problem Description

Queues and Priority Queues are data structures which are known to most computer scientists. The Queue occurs often in our daily life. There are many people lined up at the lunch time.


  Now we define that ‘f’ is short for female and ‘m’ is short for male. If the queue’s length is L, then there are 2L numbers of queues. For example, if L = 2, then they are ff, mm, fm, mf . If there exists a subqueue as fmf or fff, we call it O-queue else it is a E-queue.
Your task is to calculate the number of E-queues mod M with length L by writing a program.

Input

Input a length L (0 <= L <= 10 6) and M.

Output

Output K mod M(1 <= M <= 30) where K is the number of E-queues with length L.

Sample Input

3 8 4 7 4 8

Sample Output

6 2 1

题目链接:戳这里

思路

递推,

1、当第n位为f时,它前面是f时(ff),再前一位必须是m(mff),再前一位还必须是m(mmff),所以有f(n-4)种;

2、当第n位为f时它前面是m时(mf),再前一位必须是m(mmf),再前就任意了,所以有f(n-3)种

3、第n位是m,它前面可以是任意的,所以有f(n-1)种。

递推式:f(n)=f(n-1)+f(n-3)+f(n-4)。

根据递推式能够构造矩阵,然后矩阵快速幂。

代码

#include<cstdio>

using namespace std;

const int maxn = 4;
int L,M;
int t[5] = {0,2,4,6,9};
#define mod(x) ((x)%M)

struct Matrix{
    int a[maxn][maxn];
    void init(){
        for(int i=0;i < maxn;i++){
            for(int j=0;j < maxn;j++){
                a[i][j] = 0;
            }
        }
    }
};

Matrix mul(Matrix A,Matrix B){
    Matrix res;
    res.init();
    for(int i=0;i < maxn;i++){
        for(int j=0;j < maxn;j++){
            for(int k=0;k < maxn;k++){
                res.a[i][j] = mod(res.a[i][j] + mod(A.a[i][k]*B.a[k][j]));
            }
        }
    }
    return res;
}

Matrix poww(Matrix A,Matrix B,int n){
    Matrix res = B;
    while(n){
        if(n&1)res = mul(res,A);
        A = mul(A,A);
        n >>= 1;
    }
    return res;
}

void outPut(Matrix A){
    for(int i=0;i < maxn;i++){
        for(int j=0;j < maxn;j++){
            printf("%d ",A.a[i][j]);
        }
        printf("\n");
    }
}

int main(){
    while(~scanf("%d%d",&L,&M)){
        if(L <= 4){
            printf("%d\n",t[L]%M);
            continue;
        }
        Matrix A,B;
        A.init();
        B.init();

        A.a[0][0] = A.a[2][0] = A.a[3][0] = A.a[0][1] = A.a[1][2]=1;
        A.a[2][3]=1;
        B.a[0][0] = 9;B.a[0][1] = 6;
        B.a[0][2] = 4;B.a[0][3] = 2;
        A = poww(A,B,L-4);
        printf("%d\n",A.a[0][0]);
    }
    return 0;
}

 

转载于:https://www.cnblogs.com/yjz6/p/9799599.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值