hdu 2604 Queuing(矩阵优化递推公式)
2014-11-02 20:36
351 查看
Queuing
Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 2842 Accepted Submission(s): 1305
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
Author
WhereIsHeroFrom
递推公式f(n)=f(n-1)+f(n-3)+f(n-4)
递推过程:
现在设长度为n
1,在最后一位加m时,前面无论是什么都满足,得f(n-1);
2,在最后一位加f时,倒数后2位无论加什么都不能满足,于是讨论倒数后3位,后3位可以加mmf,即+f(n-3),现在还有 一种情况没考虑到,那就是mff,可能前面是以f结尾,于是讨论倒数后4位,在后4位上加mmff,即+f(n-4)。
得到递推公式就可以构造矩阵了。
代码:
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> using namespace std; struct matrix { int ma[10][10]; }; int mod; matrix multi(matrix x,matrix y) { matrix ans; memset(ans.ma,0,sizeof(ans.ma)); for(int i=1;i<=4;i++) { for(int j=1;j<=4;j++) { if(x.ma[i][j]) { for(int k=1;k<=4;k++) { ans.ma[i][k]=(ans.ma[i][k]+(x.ma[i][j]*y.ma[j][k])%mod)%mod; } } } } return ans; } matrix pow(matrix a,int k) { matrix ans; for(int i=1;i<=4;i++) { for(int j=1;j<=4;j++) { if(i==j) ans.ma[i][j]=1; else ans.ma[i][j]=0; } } while(k) { if(k&1) ans=multi(ans,a); a=multi(a,a); k=k>>1; } return ans; } int main() { int n; while(~scanf("%d%d",&n,&mod)) { matrix a,b; memset(a.ma,0,sizeof(a.ma)); memset(b.ma,0,sizeof(b.ma)); a.ma[1][1]=a.ma[1][3]=a.ma[1][4]=1; a.ma[2][1]=a.ma[3][2]=a.ma[4][3]=1; b.ma[1][1]=6; b.ma[2][1]=4; b.ma[3][1]=2; b.ma[4][1]=1; if(n==0) { printf("%d\n",1%mod); continue; } if(n==1) { printf("%d\n",2%mod); continue; } if(n==2) { printf("%d\n",4%mod); continue; } if(n==3) { printf("%d\n",6%mod); continue; } a=pow(a,n-3); b=multi(a,b); printf("%d\n",b.ma[1][1]); } return 0; }
相关文章推荐
- hdu 2604 Queuing(矩阵优化DP)
- HDU2604-- Queuing(矩阵快速幂优化)
- HDU 2604 Queuing (矩阵快速幂)
- hdu 2604 Queuing (矩阵快速幂)
- hdu 2604 Queuing 矩阵快速幂
- HDU2604 Queuing(矩阵快速幂)
- HDU 2604 Queuing,矩阵快速幂
- hdu 2604 Queuing(矩阵快速幂乘法)
- hdu 2604 Queuing(动态规划—>矩阵快速幂,更通用的模版)
- HDU 2604 Queuing(矩阵快速幂)
- HDU 2604 Queuing 矩阵高速幂
- 【矩阵乘法再实践】HDU 2604——queuing
- hdoj 4062 Queuing 【矩阵快速幂优化递推公式】
- HDU 2604 Queuing(矩阵快速幂)
- hdu 2604 Queuing 递推/DP 矩阵快速幂 Trie数辅助
- hdu 2604 Queuing (矩阵乘法 求递推式)
- HDU - 2604 Queuing 矩阵快速幂
- hdu---(2604)Queuing(矩阵快速幂)
- HDU 2604 Queuing (矩阵快速幂)
- HDU 2604 Queuing(矩阵快速幂)