Queuing
Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 1949 Accepted Submission(s): 911
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 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.
![](https://i-blog.csdnimg.cn/blog_migrate/bf59a6d08eb3e06ef94e640e4278ce2a.jpeg)
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.
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
Source
Recommend
lcy
首先,这是一个递推问题。mm结尾的只能由fm结尾的或者mm结尾的推来。以mf结尾的只能由mm结尾的推来,以fm结尾的只能由mf或者ff推来,以ff结尾的只能由mf推来。
F(n)=F(n-1)+F(n-3)+F(n-4)。可是正常用大数的话会TLE。后来查阅DISCUSS得知应该使用矩阵乘法。
(設f(n)為字符串為n時符合條件的字符串個數。
以字符串最後一個字符為分界點,當最後一個字符為m時前n-1個字符沒有限制,即為f(n-1);
當最後一個字符為f時就必須去除最後3個字符是fmf和fff的情況,此時最後三個字符可能為mmf和mff,
當後三個字符為mmf時,前n-3個字符沒有限制,即為f(n-3);
但是當後三個自負為mff時,後四個字符必須為mmff時前n-4個字符無限制,即為f(n-4)。
這樣就討論完了字符串的構成情況了,得出結論為:f(n) = f(n-1) + f(n-3) + f(n-4). )
其中1——4是已知的。
其中这个A矩阵是要构建的,一般是通过0-1阵,达到下图的目的,构阵方式不唯一。
#include<iostream> #include<cstdio> #include<cstring> using namespace std; int n,mod; struct Matrix{ int arr[4][4]; }; Matrix unit,init; Matrix Mul(Matrix a,Matrix b){ Matrix c; for(int i=0;i<4;i++) for(int j=0;j<4;j++){ c.arr[i][j]=0; for(int k=0;k<4;k++) c.arr[i][j]=(c.arr[i][j]+a.arr[i][k]*b.arr[k][j]%mod)%mod; c.arr[i][j]%=mod; } return c; } Matrix Pow(Matrix a,Matrix b,int k){ while(k){ if(k&1){ b=Mul(b,a); } a=Mul(a,a); k>>=1; } return b; } void Init(){ for(int i=0;i<4;i++) for(int j=0;j<4;j++){ init.arr[i][j]=0; unit.arr[i][j]=0; } unit.arr[0][0]=9, unit.arr[0][1]=6, unit.arr[0][2]=4, unit.arr[0][3]=2; init.arr[0][0]=1, init.arr[0][1]=1, init.arr[1][2]=1, init.arr[2][0]=1, init.arr[2][3]=1, init.arr[3][0]=1; } int main(){ //freopen("input.txt","r",stdin); Init(); while(~scanf("%d%d",&n,&mod)){ if(n<=4){ if(n==0) printf("0"); else if(n==1) printf("%d\n",2%mod); else if(n==2) printf("%d\n",4%mod); else if(n==3) printf("%d\n",6%mod); else if(n==4) printf("%d\n",9%mod); continue; } Matrix res=Pow(init,unit,n-4); printf("%d\n",res.arr[0][0]%mod); } return 0; }