您的位置:首页 > 产品设计 > UI/UE

hdoj2604Queuing【矩阵快速幂】

2015-11-09 13:56 543 查看

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 8
4 7
4 8

 

Sample Output

6
2
1

 

Author

WhereIsHeroFrom
 

Source

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

递推公式:f
=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
%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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息