Corresponding HDU question: Click to open the link
Queuing
Time Limit: 10000/5000 MS (Java/others) memory limit: 32768/32768 K (Java/Others)
Total submission (s): 3114 accepted submission (s): 1419
Problem descriptionqueues and Priority Queues are data structures which are known to most computer scientists. The queue occurs often in our daily life. There are getting 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.
Inputinput a length L (0 <= L <= 10 6) and M.
Outputoutput 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
The team contains F and M. For a team with a length of L, the team can be either FM, MF, mm, or ff. If a sub-team such as FMF or fff exists, it is called O-queues; otherwise, it is e-queues. Ask the number of e-Queues M in a team with a length of L.
Train of Thought: CITE others' explanations:
F (n) indicates that N people meet the conditions. If the last person is m, then the first n-1 meets the conditions, that is, F (n-1 );
If the last one is F, then this will not be able to launch the results, so consider another one: the last three may be MMF, FMF, MFF, fff, fff and FMF do not meet the meaning of the question, so we do not consider it, but if it is
MMF, then the pre-n-3 can find to meet the condition that: F (n-3); if it is MFF, and then consider one, only mmff meet the condition that: F (n-4)
So F (n) = f (n-1) + f (n-3) + f (n-4), recursive will kneel, available matrix Rapid power
Construct a matrix:
#include <stdio.h>#include <stdlib.h>#include <string.h>int f[5], mod;typedef struct{ int a[4][4];}Matrix;Matrix A, B;void Init(){ int i,j; memset(A.a, 0, sizeof(A)); memset(B.a, 0, sizeof(B)); for(i=0; i<4; i++) B.a[i][i] = 1; A.a[0][0] = 1; A.a[0][2] = 1; A.a[0][3] = 1; A.a[1][0] = 1; A.a[2][1] = 1; A.a[3][2] = 1;}Matrix Matrix_mul(Matrix X, Matrix Y){ Matrix tmp; memset(tmp.a, 0, sizeof(tmp)); int i,j,k; for(i=0; i<4; i++) for(j=0; j<4; j++) for(k=0; k<4; k++){ tmp.a[i][j] += (X.a[i][k] * Y.a[k][j]) % mod; tmp.a[i][j] %= mod; } return tmp;}void Solve(int n){ while(n) { if(n & 1) B = Matrix_mul(B, A); A = Matrix_mul(A, A); n >>= 1; }}int main(){ //freopen("in.txt", "r", stdin); int n; while(~scanf("%d%d", &n, &mod)) { Init(); f[1] = 2 % mod; f[2] = 4 % mod; f[3] = 6 % mod; f[4] = 9 % mod; if(n <= 4){ printf("%d\n", f[n]); continue; } Solve(n - 4); int i; int ans = 0; for(i=0; i<4; i++) ans += (B.a[0][i] * f[4 - i]) % mod; ans %= mod; printf("%d\n", ans); } return 0;}
Rapid matrix power -- HDU 2604