Queuing
Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 4387 Accepted Submission(s):
1936
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.
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
Recommend
递推后使用矩阵快速幂求解。
递推的规律:
1 根据题目的意思,我们可以求出F[0] = 0 , F[1] = 2 , F[2] = 4 , F[3] = 6 , F[4] = 9 , F[5] = 15
那么我们就可以构造出矩阵
| 0 1 0 0 | | F[n-4] | | F[n-3] |
| 0 0 1 0 | * | F[n-3] | = | F[n-2] |
| 0 0 0 1 | | F[n-2] | | F[n-1] |
| 1 1 0 1 | | F[n-1] | | F[n] |
从第五个开始。
题意:一个由f和m组成的串,求不存在fff和fmf的串的个数。
附上代码:
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 using namespace std; 5 struct mat 6 { 7 int m[5][5]; 8 }; 9 int mod,n; 10 11 mat mul(mat a,mat b) 12 { 13 mat c; 14 int i,j,k; 15 memset(c.m,0,sizeof(c.m)); 16 for(i=0; i<4; i++) 17 for(j=0; j<4; j++) 18 { 19 for(k=0; k<4; k++) 20 c.m[i][j]+=(a.m[i][k]*b.m[k][j])%mod; 21 c.m[i][j]%=mod; 22 } 23 return c; 24 } 25 26 mat product(mat a,int k) 27 { 28 if(k==1) return a; 29 else if(k&1) return mul(product(a,k-1),a); 30 else return product(mul(a,a),k/2); 31 } 32 33 int main() 34 { 35 int i,j,k; 36 mat a,b; 37 int x[5]= {0,2,4,6,9}; 38 while(~scanf("%d%d",&n,&mod)) 39 { 40 if(n<5) 41 { 42 printf("%d ",x[n]%mod); 43 continue; 44 } 45 memset(a.m,0,sizeof(a.m)); 46 a.m[0][1]=1; ///构建矩阵 47 a.m[1][2]=1; 48 a.m[2][3]=1; 49 a.m[3][0]=1; 50 a.m[3][1]=1; 51 a.m[3][3]=1; 52 b=product(a,n-4); 53 int ans=0; 54 for(i=0; i<4; i++) 55 ans+=(b.m[3][i]*x[i+1])%mod; 56 printf("%d ",ans%mod); 57 } 58 return 0; 59 }