Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 7245 Accepted Submission(s): 3198
php
Problem Descriptionui
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.spa
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.code
Inputblog
Input a length L (0 <= L <= 10 6) and M.ip
Outputci
Output K mod M(1 <= M <= 30) where K is the number of E-queues with length L.get
Sample Inputit
3 8 4 7 4 8io
Sample Output
6 2 1
題目連接:戳這裏
遞推,
一、當第n位爲f時,它前面是f時(ff),再前一位必須是m(mff),再前一位還必須是m(mmff),因此有f(n-4)種;
二、當第n位爲f時它前面是m時(mf),再前一位必須是m(mmf),再前就職意了,因此有f(n-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; }