题目
Queuing
Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 7245 Accepted Submission(s): 3198
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
题目链接:戳这里
思路
递推,
1、当第n位为f时,它前面是f时(ff),再前一位必须是m(mff),再前一位还必须是m(mmff),所以有f(n-4)种;
2、当第n位为f时它前面是m时(mf),再前一位必须是m(mmf),再前就任意了,所以有f(n-3)种
3、第n位是m,它前面可以是任意的,所以有f(n-1)种。
递推式:f(n)=f(n-1)+f(n-3)+f(n-4)。
根据递推式能够构造矩阵,然后矩阵快速幂。
代码
#include<cstdio>
using namespace std;
const int maxn = 4;
int L,M;
int t[5] = {0,2,4,6,9};
#define mod(x) ((x)%M)
struct Matrix{
int a[maxn][maxn];
void init(){
for(int i=0;i < maxn;i++){
for(int j=0;j < maxn;j++){
a[i][j] = 0;
}
}
}
};
Matrix mul(Matrix A,Matrix B){
Matrix res;
res.init();
for(int i=0;i < maxn;i++){
for(int j=0;j < maxn;j++){
for(int k=0;k < maxn;k++){
res.a[i][j] = mod(res.a[i][j] + mod(A.a[i][k]*B.a[k][j]));
}
}
}
return res;
}
Matrix poww(Matrix A,Matrix B,int n){
Matrix res = B;
while(n){
if(n&1)res = mul(res,A);
A = mul(A,A);
n >>= 1;
}
return res;
}
void outPut(Matrix A){
for(int i=0;i < maxn;i++){
for(int j=0;j < maxn;j++){
printf("%d ",A.a[i][j]);
}
printf("\n");
}
}
int main(){
while(~scanf("%d%d",&L,&M)){
if(L <= 4){
printf("%d\n",t[L]%M);
continue;
}
Matrix A,B;
A.init();
B.init();
A.a[0][0] = A.a[2][0] = A.a[3][0] = A.a[0][1] = A.a[1][2]=1;
A.a[2][3]=1;
B.a[0][0] = 9;B.a[0][1] = 6;
B.a[0][2] = 4;B.a[0][3] = 2;
A = poww(A,B,L-4);
printf("%d\n",A.a[0][0]);
}
return 0;
}