Queuing
Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 8207 Accepted Submission(s): 3593
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 题意:一个长度为L的串,只能由f和m组成,且子串中不能出现fff和fmf,输出有几种组合方式 解题思路:对于f(n),如果该串最后一个字母是m,那么前面n-1个字母组成的串只要符合组合方式即可,那么+f(n-1),如果最后一个字母是f,最后三个字母能组成mmf,mff才有可能符合组合方式,mmf对于他前面n-3个字母同样只要满足组合方式就行,+f(n-3),对于mff,前面一个字母肯定不能是f,那么就是最后四个字母为mmff,对于前面n-4个字母满足组合方式即可,+f(n-4),至此推出f(n)=f(n-1)+f(n-3)+f(n-4) 建立转移矩阵 0 1 0 0 0 0 1 0 0 0 0 1 1 1 0 1 建立初始矩阵 f(1) f(2) f(3) f(4)
1 #include <bits/stdc++.h> 2 using namespace std; 3 typedef long long ll; 4 typedef unsigned long long ull; 5 #define INF 0X3f3f3f3f 6 const ll MAXN = 4; 7 // const ll mod = 10000; 8 int mod; 9 //矩阵的大小 模数 10 ll n; 11 struct MAT 12 { 13 int mat[MAXN][MAXN]; 14 MAT operator*(const MAT &a) const 15 { 16 //重载矩阵乘法 17 MAT b; 18 memset(b.mat, 0, sizeof(b.mat)); 19 for (int i = 0; i < MAXN; i++) 20 { 21 for (int j = 0; j < MAXN; j++) 22 { 23 for (int k = 0; k < MAXN; k++) 24 b.mat[i][j] = (b.mat[i][j] + mat[i][k] * a.mat[k][j]); 25 b.mat[i][j] += mod; 26 b.mat[i][j] %= mod; 27 } 28 } 29 return b; 30 } 31 } start, ans; 32 MAT Mqpow(MAT base, int b) 33 { 34 MAT r; 35 memset(r.mat, 0, sizeof(r.mat)); 36 r.mat[0][0] = 2, r.mat[1][0] = 4, r.mat[2][0] = 6, r.mat[3][0] = 9; 37 //初始状态 38 while (b) 39 { 40 if (b & 1) 41 r = base * r; 42 base = base * base; 43 b >>= 1; 44 } 45 return r; 46 } 47 int main() 48 { 49 50 start.mat[0][0] = 0, start.mat[0][1] = 1, start.mat[0][2] = 0, start.mat[0][3] = 0; 51 start.mat[1][0] = 0, start.mat[1][1] = 0, start.mat[1][2] = 1, start.mat[1][3] = 0; 52 start.mat[2][0] = 0, start.mat[2][1] = 0, start.mat[2][2] = 0, start.mat[2][3] = 1; 53 start.mat[3][0] = 1, start.mat[3][1] = 1, start.mat[3][2] = 0, start.mat[3][3] = 1; 54 //建立转移矩阵 55 int f[5] = {0, 2, 4, 6, 9}; 56 while (~scanf("%d%d", &n, &mod)) 57 { 58 if (n <= 4) 59 printf("%d\n", f[n] % mod); 60 else 61 printf("%d\n", Mqpow(start, n - 4).mat[3][0]); 62 } 63 return 0; 64 }