Queuing(矩阵快速幂)
Queuing
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.
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(n)=f(n-1)+f(n-3)+f(n-4)
完整代码:
#include<iostream>
#include<cstring>
using namespace std;
typedef long long ll;
const int maxn=4;
#define mod(x) ((x)%MOD)
int n,MOD;
struct mat
{
ll m[maxn][maxn];
}unit;
mat operator *(mat a,mat b)
{
mat ret;
ll x;
for(int i=0;i<maxn;i++)
{
for(int j=0;j<maxn;j++)
{
x=0;
for(int k=0;k<maxn;k++)
{
x+=mod((ll)a.m[i][k]*b.m[k][j]);
}
ret.m[i][j]=mod(x);
}
}
return ret;
}
void init_unit()
{
for(int i=0;i<maxn;i++)
{
unit.m[i][i]=1;
}
return ;
}
mat pow_mat(mat a,ll n)
{
mat ret=unit;
while(n)
{
if(n&1)
{
ret=ret*a;
}
a=a*a;
n>>=1;
}
return ret;
}
int main()
{
init_unit();
while(cin>>n>>MOD)
{
if(n<=4)
{
cout<<num[n]%MOD<<endl;
}
else
{
mat a,b;
memset(a.m,0,sizeof(a.m));
a.m[0][0] = 6;
a.m[1][0] = 4;
a.m[2][0] = 2;
a.m[3][0] = 1;
b.m[0][0]=1;b.m[0][1]=0;b.m[0][2]=1;b.m[0][3]=1;
b.m[1][0]=1;b.m[1][1]=0;b.m[1][2]=0;b.m[1][3]=0;
b.m[2][0]=0;b.m[2][1]=1;b.m[2][2]=0;b.m[2][3]=0;
b.m[3][0]=0;b.m[3][1]=0;b.m[3][2]=1;b.m[3][3]=0;
b=pow_mat(b,n-3);
b=b*a; /* 注意矩阵乘法a*b和b*a是不一样的 */
cout<<b.m[0][0]<<endl;
}
}
return 0;
}