hdoj2604Queuing【矩阵快速幂】

来源:互联网 发布:如何看待辛亥革命 知乎 编辑:程序博客网 时间:2024/06/05 16:23



Queuing

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


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 84 74 8
 

Sample Output
621
 

Author
WhereIsHeroFrom
 

Source
HDU 1st “Vegetable-Birds Cup” Programming Open Contest
 

递推公式:f[n]=f[n-1]+f[n-3]+f[n-4];

初始矩阵:1 1 0 0

                    0 0 1 0

                   1 0 0 1

                   1 0 0 0

#include<cstdio>#include<cstdlib>#include<cstring>#include<algorithm>#include<cmath>using namespace std;int a[5][5];int ans[5][5];int M;void Mulit(int A[5][5],int B[5][5]){int D[5][5]={0};for(int i=0;i<4;++i){for(int k=0;k<4;++k){if(A[i][k]){for(int j=0;j<4;++j){D[i][j]=(D[i][j]+A[i][k]*B[k][j])%M;}}}}for(int i=0;i<4;++i){for(int j=0;j<4;++j){A[i][j]=D[i][j];}}}void Matrix(int A[5][5],int n){memset(ans,0,sizeof(ans));ans[0][0]=ans[1][1]=ans[2][2]=ans[3][3]=1;while(n){if(n&1)Mulit(ans,a);Mulit(a,a);n>>=1;}}int main(){int n,i,j,k;int num[5]={1,2,4,6,9};while(scanf("%d%d",&n,&M)!=EOF){if(n<=4){printf("%d\n",num[n]%M);}else {memset(a,0,sizeof(a));a[0][0]=1;a[2][0]=1;a[3][0]=1;a[0][1]=1;a[1][2]=1;a[2][3]=1;Matrix(a,n-4);int S=9*ans[0][0]+6*ans[1][0]+4*ans[2][0]+2*ans[3][0];printf("%d\n",S%M);}}return 0;}
0 0
原创粉丝点击