对应HDU题目:点击打开链接
Queuing
Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 3114 Accepted Submission(s): 1419
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
题意:队伍里面有f和m, 对于长度为L的队伍,可组成这样的队伍:fm, mf, mm, ff。如果存在 fmf 或 fff 这样的子队伍,就称队伍为O-queues,否则为E-queues。问长度为L的队伍里E-queues的数目模M是多少。
思路:引用别人解释:
用f(n)表示n个人满足条件的结果,那么如果最后一个人是m的话,那么前n-1个满足条件即可,就是f(n-1);
如果最后一个是f那么这个还无法推出结果,那么往前再考虑一位:那么后三位可能是:mmf, fmf, mff, fff,其中fff和fmf不满足题意所以我们不考虑,但是如果是
mmf的话那么前n-3可以找满足条件的即:f(n-3);如果是mff的话,再往前考虑一位的话只有mmff满足条件即:f(n-4)
所以f(n)=f(n-1)+f(n-3)+f(n-4),递推会跪,可用矩阵快速幂
构造一个矩阵:
#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; }