hdu 2604 Queuing(推推推公式+矩阵快速幂)
Posted 抓不住Jerry的Tom
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了hdu 2604 Queuing(推推推公式+矩阵快速幂)相关的知识,希望对你有一定的参考价值。
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 2 L numbers of queues. For example, if L = 2, then they are ff, mm, fm, mf .
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 2 L 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.
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的字符串,让你找出满题条件的串的个数对m取余的数。如果这个串中不含fff和fmf就说这个串是满足条件的。
假设现有长度为n的串s,f(n)是s串满足条件的答案。f(n)怎么推出来捏?
如果s的最后一位为m,那么就加上f(n-1),因为在长度为n-1的满足条件的串后面加上一个m所得到的串肯定也满足条件。
如果s的最后一位为f,那么s的最后三位只有mmf和mff两种情况!继续讨论!
如果s以mmf结尾,那么加上f(n-3),因为在长度为n-3的满足条件的串后面加上一个mmf所得到的串肯定也满足条件。
那如果s以mff结尾呢?向前思考一位,倒数第四位只能是m,也就是此时s是以mmff结尾的,再加上f(n-4)岂不是美滋滋?
综上f(n)=f(n-1)+f(n-3)+f(n-4)。无耻的再盗张图...OTZ...
代码如下:
1 #include <bits/stdc++.h> 2 3 using namespace std; 4 const int N=4; 5 int l,m; 6 struct Matrix 7 { 8 long long int mat[N][N]; 9 }matrix; 10 void init() 11 { 12 memset(matrix.mat,0,sizeof matrix.mat); 13 matrix.mat[0][0]=1; 14 matrix.mat[0][1]=0; 15 matrix.mat[0][2]=1; 16 matrix.mat[0][3]=1; 17 for (int i=1;i<N;++i) 18 { 19 for (int j=0;j<N;++j) 20 { 21 if (i==j+1) 22 matrix.mat[i][j]=1; 23 } 24 } 25 } 26 Matrix operator * (Matrix a,Matrix b) 27 { 28 Matrix c; 29 for (int i=0;i<N;++i) 30 { 31 for (int j=0;j<N;++j) 32 { 33 c.mat[i][j]=0; 34 for (int k=0;k<N;++k) 35 c.mat[i][j]+=a.mat[i][k]*b.mat[k][j]; 36 c.mat[i][j]%=m; 37 } 38 } 39 return c; 40 } 41 Matrix Pow (int n) 42 { 43 Matrix t; 44 if (n==1) 45 return matrix; 46 if (n&1) 47 return matrix*Pow(n-1); 48 else 49 { 50 Matrix temp=Pow(n>>1); 51 return temp*temp; 52 } 53 } 54 int main() 55 { 56 //freopen("de.txt","r",stdin); 57 long long int f[5]; 58 f[0]=0; 59 f[1]=2; 60 f[2]=4; 61 f[3]=6; 62 f[4]=9; 63 while (~scanf("%d%d",&l,&m)) 64 { 65 init(); 66 if (l<=4) 67 { 68 printf("%lld\n",f[l]%m); 69 continue; 70 } 71 Matrix temp=Pow(l-4); 72 long long int ans=0; 73 for (int i=0;i<N;++i) 74 { 75 ans += temp.mat[0][i]*f[N-i]; 76 ans%=m; 77 } 78 printf("%lld\n",ans); 79 } 80 return 0; 81 }
以上是关于hdu 2604 Queuing(推推推公式+矩阵快速幂)的主要内容,如果未能解决你的问题,请参考以下文章