Queuing
Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 4870 Accepted Submission(s): 2158
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.
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
1 根据题目的意思,我们可以求出F[0] = 0 , F[1] = 2 , F[2] = 4 , F[3] = 6 , F[4] = 9 , F[5] = 15
2 那么根据上面前5项我们可以求出n >= 5的时候 F[n] = F[n-1]+F[n-3]+F[n-4]
2 那么根据上面前5项我们可以求出n >= 5的时候 F[n] = F[n-1]+F[n-3]+F[n-4]
知道了递推公式了先瞎暴力了一发TLE了,很明显是不能暴力过的,因为是线性递推,那么考虑用矩阵快速幂,瞎JB一波就可以了。
#include<stdio.h>
#include<algorithm>
#include<string.h>
using namespace std;
int n,k;
int mod;
struct Matrix
{
int m[10][10];
}M;
Matrix Mult(Matrix a,Matrix b) //矩阵乘法
{
Matrix ans;
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
ans.m[i][j]=0;
for(int k=0;k<n;k++)
{
ans.m[i][j]+=a.m[i][k]*b.m[k][j];
ans.m[i][j]%=mod;
}
}
}
return ans;
}
Matrix quickpow(Matrix a,int b)
{
Matrix ans;
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
if(i==j)
ans.m[i][j]=1;
else
ans.m[i][j]=0;
}
}
while(b)
{
if(b&1)
ans=Mult(ans,a);
a=Mult(a,a);
b/=2;
}
return ans;
}
int a[10];
int main()
{
while(scanf("%d%d",&k,&mod)!=EOF)
{
a[0]=0;a[1]=2;a[2]=4;a[3]=6;a[4]=9;a[5]=15;
if(k<=5)
{
printf("%d\n",a[k]%mod);
continue;
}
n=4;
Matrix M,N;
for(int i=0;i<4;i++)
{
for(int j=0;j<4;j++)
N.m[i][j]=M.m[i][j]=0;
}
N.m[0][0]=15;
N.m[1][0]=9;
N.m[2][0]=6;
N.m[3][0]=4;
for(int i=0;i<4;i++)
{
for(int j=0;j<4;j++)
N.m[i][j]%=mod;
}
for(int i=0;i<n;i++)
{
if(i!=1)
M.m[0][i]=1;
}
for(int i=1;i<n;i++)
M.m[i][i-1]=1;
/*for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
printf("%d ",M.m[i][j]);
}
printf("\n");
}*/
M=quickpow(M,k-5);
M=Mult(M,N);
printf("%d\n",M.m[0][0]);
}
return 0;
}