前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >HDU 2604 Queuing(矩阵快速幂)

HDU 2604 Queuing(矩阵快速幂)

作者头像
ShenduCC
发布2018-04-26 16:32:47
4070
发布2018-04-26 16:32:47
举报
文章被收录于专栏:算法修养

Queuing

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

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

找到递推关系 s[n]=s[n-1]+s[n-3]+s[n-4];

代码语言:javascript
复制
#include <iostream>
#include <string.h>
#include <stdio.h>
#include <algorithm>
#include <math.h>
#include <stdlib.h>

using namespace std;
struct Node
{
    int a[10][10];
};
int n,m;
Node multiply(Node a,Node b)
{
    Node c;
    memset(c.a,0,sizeof(c.a));
    for(int i=0;i<4;i++)
    {
        for(int j=0;j<4;j++)
        {
            if(!a.a[i][j]) continue;
            for(int k=0;k<4;k++)
            {
                (c.a[i][k]+=(a.a[i][j]*b.a[j][k])%m)%=m;
            }
        }
    }
    return c;
}
Node get(Node a,int x)
{
    Node c;
    memset(c.a,0,sizeof(c.a));
    for(int i=0;i<4;i++)
        c.a[i][i]=1;
    for(x;x;x>>=1)
    {
        if(x&1) c=multiply(c,a);
        a=multiply(a,a);
    }
    return c;
}
int main()
{
    while(scanf("%d%d",&n,&m)!=EOF)
    {
    if(n==0)
    {printf("1\n");continue;}
    else if(n==1)
    {printf("2\n");continue;}
    else if(n==2)
    {printf("4\n");continue;}
    else if(n==3)
    {printf("6\n");continue;}
    else
    {
        Node a;
        a.a[0][0]=1;a.a[0][1]=0;a.a[0][2]=1;a.a[0][3]=1;
        a.a[1][0]=1;a.a[1][1]=0;a.a[1][2]=0;a.a[1][3]=0;
        a.a[2][0]=0;a.a[2][1]=1;a.a[2][2]=0;a.a[2][3]=0;
        a.a[3][0]=0;a.a[3][1]=0;a.a[3][2]=1;a.a[3][3]=0;
        Node b;
        memset(b.a,0,sizeof(b.a));
        b.a[0][0]=6;b.a[1][0]=4;b.a[2][0]=2;b.a[3][0]=1;
        a=get(a,n-3);
        a=multiply(a,b);
        printf("%d\n",a.a[0][0]);

    }

    }
    return 0;

}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2016-04-21 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档